DOM 작업하기
DOM 작업
DOM 레이어는 HTML 페이지를 유형화된 노드들의 트리로 모델링합니다. Document는 진입점이자 노드 팩토리이며; Element와 Node는 조작 및 순회 API을 수행합니다.
노드 생성
Document.create_element(), create_text_node(), create_comment(), create_document_fragment()은(는) 노드를 생성합니다; append_child()는 그것들을 연결합니다:
from aspose_html.dom import Document
doc = Document()
el = doc.create_element("div")
doc.append_child(el)Attributes
Element.set_attribute(), get_attribute(), has_attribute(), remove_attribute()은(는) 마크업 속성을 관리하고; Attr와 NamedNodeMap는 이를 객체로 노출합니다:
from aspose_html.dom import Document
doc = Document()
el = doc.create_element("div")
el.set_attribute("class", "foo")
el.set_attribute("id", "bar")
doc.append_child(el)트리 연산
Node은 구조 툴킷을 제공합니다: insert_before(), remove_child(), replace_child(), clone_node(), 및 contains(), 그리고 child_nodes, parent_node, first_child 접근자와 서브트리 텍스트용 text_content을 추가로 제공합니다. get_root_node()과 has_child_nodes()은 구조적 질문에 직접 답합니다.
조회 및 탐색
Document.get_element_by_id()은 id 로 요소를 검색합니다. NodeList과 HTMLCollection는 결과 집합을 보유합니다; NodeIterator와 TreeWalker(와 함께 NodeFilter)는 문서 순서대로 서브트리를 순회합니다.
변이 관찰
MutationObserver은 트리 변경을 MutationRecord 항목으로 기록하며, 구조 편집에 반응하기 위한 표준 옵저버 패턴을 반영합니다.
팁 및 모범 사례
- 모든 노드는 소유
Document을 통해 생성하세요 — 노드는 문서 범위이며;Document.import_node()또는adopt_node()를 사용해 문서 간에 이동할 수 있습니다. - 전체 서브트리 텍스트에는 수동
Text노드 조작보다text_content을 사용하는 것이 좋습니다. - 단일
append_child()이전에 노드 배치를 조립하려면DocumentFragment를 사용하십시오. - 누락된 속성이 의미가 있을 때
get_attribute()전에has_attribute()를 확인하십시오.
일반적인 문제
| 문제 | 원인 | 수정 |
|---|---|---|
| 노드가 잘못된 문서에 표시됩니다 | 다른 Document에 의해 생성된 노드 | 먼저 import_node() 또는 adopt_node()로 이동하세요 |
| 속성 조회가 아무 것도 반환하지 않습니다 | 요소에 속성이 설정되지 않았습니다 | has_attribute() 로 보호 |
| 하위 트리 텍스트가 비어 있습니다 | 자식이 연결되기 전에 text_content을(를) 읽는 중 | 자식을 연결하고, 그 다음 읽기 |
FAQ
어떤 클래스가 새 요소를 생성합니까?
Document — 그 create_element() 메서드는 요소를 위한 팩토리이며, 텍스트, 주석 및 조각을 위한 형제 팩토리도 제공합니다.
두 문서 사이에서 서브트리를 어떻게 이동합니까?
Document.import_node()를 사용하여 복사하거나 adopt_node()를 사용하여 전송한 다음, append_child()로 붙입니다.
트리 변경에 대한 API 옵저버가 있나요?
예 — MutationObserver은 구조 및 속성 변경을 설명하는 MutationRecord 배치를 제공합니다.
API Reference 요약
| 클래스/메서드 | 설명 |
|---|---|
Document.create_element | 요소 노드를 생성합니다 |
Document.get_element_by_id | id로 요소를 찾기 |
Element.set_attribute | 마크업 속성을 설정합니다 |
Node.insert_before | 참조 자식 앞에 노드를 삽입하기 |
Node.clone_node | 노드 또는 서브트리를 복사하기 |
MutationObserver | 트리 변이를 관찰하기 |
TreeWalker | 필터링된 문서 순서 순회 |