본문 바로가기

Web 기초

[Web] 웹 기초 (20) - JavaScript #13 DOM Object

문서객체모델 (Document Object Model)

사용메소드

document.getElementById('아이디')
document.querySelector('선택자')
document.getElementsByName('이름') // name 속성
document.getElementsByClassName('클래스')
document.querySelectorAll('선택자')

 


 

동적으로 문서객체 생성

function first(){ 
  let header = document.createElement('h1');
  let textNode = document.createTextNode('Hello DOM');

  header.appendChild(textNode);
  document.body.appendChild(header);
}
first();
  • h1 태그를 이용해 헤드라인 만들어주고
  • appendChild 로 append 해주기

 

버튼추가, 버튼에 이벤트 추가

//button
let btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('value', '버튼');
btn.setAttribute('id', 'btn');
btn.style.width='200px';
btn.style.height='80px';

// 버튼 추가
document.body.appendChild(btn);

// 만든 버튼에 이벤트 추가
let b = document.getElementById('btn');

b.onclick=function(){
  alert('버튼클릭');
}

 

input 텍스트 박스 추가, 이벤트 추가

//text box(input type='text')
let inputBox = document.createElement('input');
inputBox.setAttribute('type', 'text');
inputBox.setAttribute('value', '텍스트를 입력하세요');
inputBox.setAttribute('id', 'txt');

document.body.appendChild(inputBox);
let t = document.getElementById('txt');

// input 텍스트상자 초기화시키는 이벤트 추가
t.onclick=function(){
  txt.value = '';
}

 

br 태그 추가해서 줄바꿈

//br
let br = document.createElement('br');
document.body.appendChild(br);
document.body.appendChild(inputBox);