DOM (Document Object Model)

JavaScript · 2021. 6. 2. 23:44

개념

  • 브라우저에서 html을 조작하게 해주는 프로그래밍 인터페이스
    • 자바스크립트에서 DOM은 document에 객체에 구현된다.
    • 자바스크립트와는 독립된 것이며 다른 프로그래밍 언어에서도 사용할 수 있는 일종의 브라우저 표준(Standard)이다.

구조

  • DOM은 트리 구조를 가진다(부모 하나에 자식 여럿. 부모는 둘이 될 수 없다.)
  • DOM은 문서를 노드와 객체로 나타낸다
  • DOM 조회에는 console.dir를 사용한다.

html 조작을 위한 <script>태그의 위치

  • <head> 태그 안에 자바스크립트를 쓰면 브라우저는 html 요소 읽기를 멈추고 자바스크립트 코드를 실행한다. 따라서 <body></body>태그의 가장 하단에 <script>를 써야 html 요소들을 모두 불러온 후에 자바스크립트로 이를 조작할 수 있다.

DocumentFragment

  • 부모가 없는 document 객체
  • Document.createDocumentFragment();로 빈 document 객체를 생성할 수 있다.
  • DocumentFragment에 필요한 엘리먼트를 추가하고 이를 다시 원래의 DOM에 추가하면(append) 불필요한 DOM의 심도를 줄여서 브라우저 렌더링 속도를 향상할 수 있다.
  • <template>엘리먼트의 content 속성(template.content)은 <template>엘리먼트의 DocumentFragment이다.
    • 그러나 DocumentFragment 객체의 요소는 read-only이기 때문에 event를 받아올 수는 없다.

참고:
-코드스테이츠 유어클래스
-https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction#dom_and_javascript
-https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment
-https://developers.google.com/speed/docs/insights/browser-reflow?csw=1
-https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment
-https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template