on
[JS] DOM(Document Object Model)
[JS] DOM(Document Object Model)
DOM은 HTML 또는 XML document와 상호작용하고 표현하는 API 이다.
DOM은 brower에서 로드되며, 노드 트리로 표현하는 document 모델이다.
이것을 이용해서 document의 모든 node에 접근하고 상호작용할 수 있도록 browser에서 코드를 실행할 수 있다.
여기서 상호작용한다는 의미는 노드들을 생성, 이동 및 변경할 수 있다는 뜻으로 생각하면 좋다.
이와 같은 이유로 Web에서 가장 많이 사용되는 API 중 하나이다.
DOM 출처:
https://developer.mozilla.org/ko/docs/Glossary/DOM
DOM은 크게 CRUD로 나눌 수 있다.
CRUD(Create, Read, Update ,Delete)
CREATE
: 자바스크립트를 통해 원하는 태그를 생성할 수 있다.
document.createElement('div');
APPEND
: document의 원하는 위치에 요소를 넣을 수 있다.
document.body.append('tag'); //추가로 마지막 자식요소로 넣을 수 있는 appendchild도 있다.
READ
: 원하는 태그의 정보를 가져올 수 있다.
document.querySelector('#id'); document.querySelectorAll('.kim'); //kim라는 클래스를 가진 모든 태그를 불러옴
UPDATE
: 일반 텍스트 또는 클래스 등을 넣어서 내용을 업데이트할 수 있다.
This is some text!
let text = document.getElementById('divA').textContent; document.getElementById('divA').textContent = 'This text is different!';
DELETE
: 태그들을 하나씩 지우거나 모든 자식 엘리먼트를 지울 수 있다.
//모든 자식 엘리먼트를 지울 때 document.body.append('tag');//공백을 넣어줌 const container = document.querySelector('#container'); while (container.firstChild) { container.removeChild(container.firstChild); } //위 코드는 자식 엘리먼트가 남아있지 않을 때까지 첫 번째 자식엘리먼트를 삭제하는 코드. const container = document.querySelector('#container'); while (container.children.length > 1) { container.removeChild(container.lastChild); } //위 코드는 자식 엘리먼트를 하나만 남기게 할 수 있다. const tweets = document.querySelectorAll('.tweet') tweets.forEach(function(tweet){ tweet.remove(); }) // or for (let tweet of tweets){ tweet.remove() } //직접 클래스 이름이 tweet인 엘리먼트만 찾아서 지우는 방법도 있다.
from http://codingbucks.tistory.com/52 by ccl(A) rewrite - 2021-10-27 00:00:37