[240513] 39장 DOM (2)

노드 탐색

  • Node, Element 인터페이스는 트리 탐색 프로퍼티 제공
  • 노트 탐색 프로퍼티는 모두 접근자 프로퍼티, getter 만 존재

  • Node.prototype
    • parentNode
    • previousSibling
    • firstChild
    • childNodes
  • Element.prototype
    • previousElementSibling
    • nextElementSibling

1. 공백 테스트 노드

  • HTML 요소 사이의 스페이스, 탭, 줄바꿈 등의 공백 문자는 텍스트 노드 생성

2. 자식 노드 탐색

  • Node.prototype.childNodes
    • 자식 노드 모두를 NodeList 담아 반환
    • 텍스트 노드 포함될 수도 있음
  • Element.prototype.children
    • 자식 노드 모두를 HTMLCollection 담아 반환
    • 텍스트 노트 포함 X
  • Node.prototype.firstChild
    • 첫번째 자식 노드 반환
    • 텍스트 노드 이거나 요소 노드
  • Node.prototype.lastChild
    • 마지막 자식 노드를 반환
    • 텍스트 노드 이거나 요소 노드
  • Element.prototype.firstElementChild
    • 첫 번째 자식 요소 노드
    • 요소 노드만 반환
  • Element.prototype.lastElementChild
    • 마지막 자식 노드
    • 요소 노드만 반환
const $fruits = document.getElementById('fruits');
$fruits.childNodes;
$firsts.children

3. 자식 노드 존재 확인

  • Node.prototype.hasChildNodes
    • 텍스트 노드 포함함
  • children.length , childElementCount
    • 텍스트 노드 포함 X

4. 요소 노드의 텍스트 노드 탐색

  • firstChild 프로퍼티로 접근 가능
    • 첫번째 자식 노드를 반환함

5. 부모 노드 탐색

  • NodeParentNode
  • 텍스트 노드는 리프 노드 이므로 부모 노드가 텍스트 노드인 경우는 없음

6. 형제 노드 탐색

  • 어트리뷰트 노드는 요소 노드와 연결되어 있지만 부모 노드가 같은 형제 노드가 아니기 때문에 반환 X
  • Node.prototype.previousSibling
  • Node.prototype.nextSibling
    • 텍스트 노드일 수도 있음
  • Element.prototype.previousElementSibling
  • Element.prototype.nextElementSibling
    • 요소 노드만 반환

노드 정보 취득

  • Node.prototype.nodeType
    • 노드 타입을 나타내는 상수 반환
    • Node 에 정의되어있음
    • Node.ELEMENT_NODE : 상수 1 반환 (요소노드)
    • Node.TEXT_NODE : 상수 3 ( 텍스트 노드 )
    • Node.DOCUMENT_NODE: 상수 9 ( 문서 노드 )
  • Node.prototype.nodeName
    • 노드의 이름을 문자열로 반환
    • 요소노드: 대문자 문자열로 태그 이름 반환 (UL, LI 등)
    • 텍스트 노드: 문자열 #text 로 반환
    • 문서노드: 문자열 #document 반환

요소 노드의 텍스트 조작

1. nodeValue

  • Node.prototype.nodeValue
    • setter , getter 모두 존재
    • 노드 객체의 값 반환 ( 텍스트 노드의 텍스트 )
    • 텍스트 노드가 아니면 null 반환
    • firstChild 사용해서 텍스트 노드 취득해서 변환

2. textContent

  • Node.prototype.textContent
    • setter , getter 모두 존재
    • 요소 노드의 콘텐츠 영역 ( 시작 태그와 종료 태그 사이) 모든 텍스트 반환
    • HTML 마크업은 무시됨
  • 비슷한걸로 innerText 가 있는데 CSS에 순종적이여서 권장하지 않음

Categories:

Updated:

Leave a comment