DocumentFragment
인터페이스는 부모가 없는 아주 작은 document 객체를 나타냅니다. Document
의 경량화된 버전으로 사용되며 표준문서와 같이 노드로 구성된 문서 구조의 일부를 저장합니다. 중요한 차이점은 DocumentFragment
는 활성화된 문서 트리 구조의 일부가 아니기 때문에 fragment를 변경해도 문서에는 영향을 미치지 않으며(reflow 포함) 성능에도 영향이 없다는 점입니다.
생성자
DocumentFragment()
- 새로운
DocumentFragment
객체를 생성하여 반환합니다.
속성
이 인터페이스는 특정한 속성이 없지만 부모인 Node
, ParentNode
의 속성을 상속합니다.
ParentNode.children
Read onlyDocumentFragment
객체의 자식Element
를 전부 포함하는 실시간HTMLCollection
을 반환합니다.ParentNode.firstElementChild
Read onlyDocumentFragment
객체의 첫번째 자식Element
를 반환합니다. 없으면null
을 반환합니다.ParentNode.lastElementChild
Read onlyDocumentFragment
객체의 마지막 자식Element
를 반환합니다. 없으면null
을 반환합니다.ParentNode.childElementCount
Read onlyDocumentFragment
가 가진 자식 수를unsigned long
타입으로 반환합니다.
메서드
이 인터페이스는 부모인 Node
와 ParentNode
인터페이스의 메서드를 상속합니다.
DocumentFragment.querySelector()
DocumentFragment
내 지정된 선택자와 일치하는 첫번째Element
노드를 반환합니다.DocumentFragment.querySelectorAll()
DocumentFragment
내 지정된 선택자와 일치하는 모든Element
노드를NodeList
형태로 반환합니다.DocumentFragment.getElementById()
DocumentFragment
내 지정된 ID와 일치하는 첫번째Element
노드를 반환합니다. 기능적으로Document.getElementById()
와 동일합니다.
사용법
DocumentFragment
의 일반적인 용도는 DocumentFragment
를 생성하고, 그 안에서 DOM 하위 트리를 조립한 다음, appendChild()
나 insertBefore()
와 같은 Node
인터페이스 메서드를 사용하여 DOM에 삽입하는 것입니다. 이렇게 하면 DocumentFragment
의 노드들이 DOM으로 이동되고 빈 DocumentFragment
만 남게 됩니다. 모든 노드가 한 번에 문서에 삽입되기 때문에 노드를 개별로 하나씩 삽입할 때마다 리플로우와 렌더링을 해주는 대신 단 한 번의 리플로우와 렌더링만 발생하게 됩니다.
이 인터페이스는 웹 컴포넌트를 사용할 때도 매우 유용합니다: <template>
요소는 HTMLTemplateElement.content
속성에 DocumentFragment
를 포함하고 있습니다.
빈 DocumentFragment
는 document.createDocumentFragment()
메서드나 생성자를 이용하여 만들 수 있습니다.
예제
HTML
<ul id="list"></ul>
JavaScript
var list = document.querySelector('#list')
var fruits = ['Apple', 'Orange', 'Banana', 'Melon']
var fragment = new DocumentFragment()
fruits.forEach(function (fruit) {
var li = document.createElement('li')
li.innerHTML = fruit
fragment.appendChild(li)
})
list.appendChild(fragment)
결과
명세
표준 | 상태 | 비고 |
---|---|---|
DOM The definition of 'DocumentFragment' in that specification. |
Living Standard | Added the constructor and the implementation of ParentNode . |
Selectors API Level 1 The definition of 'DocumentFragment' in that specification. |
Obsolete | Added the querySelector() and querySelectorAll() methods. |
Document Object Model (DOM) Level 3 Core Specification The definition of 'DocumentFragment' in that specification. |
Obsolete | No change from Document Object Model (DOM) Level 2 Core Specification |
Document Object Model (DOM) Level 2 Core Specification The definition of 'DocumentFragment' in that specification. |
Obsolete | No change from Document Object Model (DOM) Level 1 Specification |
Document Object Model (DOM) Level 1 Specification The definition of 'DocumentFragment' in that specification. |
Obsolete | Initial definition |
브라우저 호환성
BCD tables only load in the browser