HTML요소를 Object처럼 조작할 수 있는 Model
DOM을 이용하면 HTML로 구성된 웹 페이지를 동적으로 움직이게 만들 수 있다.
HTML의 요소를 console.dir로 출력해보면, 객체의 모습으로 출력된다.
let element = document.querySelector('div');
console.dir(element);
// 결과
accept: ""
accessKey: ""
align: ""
alt: ""
...
DOM을 사용하여 HTML에 CRUD(Create, Read, Update, Delete)를 할 수 있다.
HTML내에 새로운 요소를 추가하고 싶을 때 document.createElement()를 사용한다.
const tweet = document.createElement('div');
document.body.append(twwet); // body영역 안에 div영역이 추가된다.
특정 id, class, tag를 가진 요소를 찾아서 가져오고 싶을 때 querySelector()를 사용한다.
const elGetClass = document.querySelector('.class');
const elGetId = document.querySelector('#id');
const elGetTag = document.querySelector('div');
새로 만든 태그에 문자열을 넣고 싶을 때 textContent나 .value를 사용하면 된다.
tweet.textContent = 'new'; // <div>new</div>
태그에 class나 id를 추가하고 싶을때 classList, .id를 사용하면 된다.
tweet.classList.add('tweet'); // <div class = 'tweet'>
tweet.id = 'container'; // <div id = 'container'>
그 외 다른 속성도 setAttribute()를 통해 추가할 수 있다.
tweet.setAttribute('name', 'new'); // <div name = 'new'>
document.querySelector('#container').innerHTML = '';
위의 코드처럼 innerHTML을 사용하여 container라는 id를 가지고 있는 태그 아래에 있는 모든 요소를 삭제할 수 있다.
다만, innerHTML은 보안상의 이슈가 있으므로 권장하지 않는다.
while(container.firstchild){
container.removeChild(container.firstchild);
}
위의 코드처럼 container의 자식요소가 다 삭제될 때까지 반복문을 돌리는 식으로 사용할 수 있다.
const del = document.querySelectorAll('.tweet');
del.forEach(function(i){
i.remove();
}
del변수에 할당된 tweet클래스를 가진 요소를 i에 할당하며 순회하여 삭제하는 방식이다.
키보드가 타이핑되고, 클릭되고, 스크롤되는 등의 행동들이 모두 Event이다.
앞으로 더 학습하겠지만, 현재 배운 event는 onclick, onkeyup이다.
tweet.onkeyup = function(){
element.classList.add('hide')
}
위의 코드는 tweet에 할당된 영역에 타이핑이 쳐질 경우, element에 할당된 요소에 hide라는 클래스가 추가된다.
addEvenListener()로도 구현이 가능하다.
tweet.addEventListener('keyup', function(){
element.classList.add('hide');
}