JavaScript DOM Traversal


자바스크립트에서 DOM 트래버설(DOM Traversal)은 DOM 트리 내에서 노드를 탐색하는 과정을 말합니다. DOM 트리의 각 요소는 노드로 표현되며, 이러한 노드 간의 관계를 통해 부모, 자식, 형제 노드를 탐색할 수 있습니다. DOM 트래버설을 이해하고 활용하면 특정 요소를 선택하고 조작하는 작업이 쉬워집니다. 여기서는 DOM 트래버설에 관련된 다양한 방법을 상세히 설명하겠습니다.

1. 기본 개념

DOM 트리는 계층적 구조로, 노드는 부모-자식 관계를 통해 연결됩니다. 주요 노드 관계는 다음과 같습니다:

  • 부모 노드 (Parent Node): 현재 노드를 포함하는 상위 노드.
  • 자식 노드 (Child Node): 현재 노드에 포함된 하위 노드.
  • 형제 노드 (Sibling Node): 같은 부모를 공유하는 노드.

2. 주요 트래버설 메서드와 속성

2.1 부모 노드 탐색

  • parentNode: 부모 노드를 반환합니다. 최상위 노드인 경우 null을 반환합니다.
const childNode = document.getElementById('child');
const parentNode = childNode.parentNode;
console.log(parentNode);

2.2 자식 노드 탐색

  • childNodes: 자식 노드를 포함한 NodeList를 반환합니다.
  • firstChild: 첫 번째 자식 노드를 반환합니다.
  • lastChild: 마지막 자식 노드를 반환합니다.
const parentNode = document.getElementById('parent');
const childNodes = parentNode.childNodes;
console.log(childNodes);

const firstChild = parentNode.firstChild;
console.log(firstChild);

const lastChild = parentNode.lastChild;
console.log(lastChild);

2.3 형제 노드 탐색

  • previousSibling: 이전 형제 노드를 반환합니다.
  • nextSibling: 다음 형제 노드를 반환합니다.
const currentNode = document.getElementById('current');
const previousSibling = currentNode.previousSibling;
console.log(previousSibling);

const nextSibling = currentNode.nextSibling;
console.log(nextSibling);

2.4 특정 타입의 자식 노드 탐색

  • children: 자식 요소(요소 노드만)를 포함한 HTMLCollection을 반환합니다.
  • firstElementChild: 첫 번째 자식 요소 노드를 반환합니다.
  • lastElementChild: 마지막 자식 요소 노드를 반환합니다.
  • previousElementSibling: 이전 형제 요소 노드를 반환합니다.
  • nextElementSibling: 다음 형제 요소 노드를 반환합니다.
const parentNode = document.getElementById('parent');
const children = parentNode.children;
console.log(children);

const firstElementChild = parentNode.firstElementChild;
console.log(firstElementChild);

const lastElementChild = parentNode.lastElementChild;
console.log(lastElementChild);

const currentElement = document.getElementById('current');
const previousElementSibling = currentElement.previousElementSibling;
console.log(previousElementSibling);

const nextElementSibling = currentElement.nextElementSibling;
console.log(nextElementSibling);

3. 특정 요소 선택

3.1 querySelectorquerySelectorAll

  • element.querySelector(selector): 주어진 CSS 선택자와 일치하는 첫 번째 요소를 반환합니다.
  • element.querySelectorAll(selector): 주어진 CSS 선택자와 일치하는 모든 요소를 NodeList로 반환합니다.
const parent = document.getElementById('parent');
const firstChild = parent.querySelector('.child');
console.log(firstChild);

const allChildren = parent.querySelectorAll('.child');
console.log(allChildren);

3.2 getElementsByClassName, getElementsByTagName, getElementById

  • document.getElementsByClassName(className): 특정 클래스를 가진 모든 요소를 HTMLCollection으로 반환합니다.
  • document.getElementsByTagName(tagName): 특정 태그 이름을 가진 모든 요소를 HTMLCollection으로 반환합니다.
  • document.getElementById(id): 특정 ID를 가진 요소를 반환합니다.
const elementsByClassName = document.getElementsByClassName('myClass');
console.log(elementsByClassName);

const elementsByTagName = document.getElementsByTagName('div');
console.log(elementsByTagName);

const elementById = document.getElementById('myId');
console.log(elementById);

4. 예제: 트래버설을 활용한 조작

4.1 부모 요소의 배경색 변경

const childNode = document.getElementById('child');
const parentNode = childNode.parentNode;
parentNode.style.backgroundColor = 'lightblue';

4.2 모든 자식 요소의 텍스트 변경

const parentNode = document.getElementById('parent');
const children = parentNode.children;

for (let i = 0; i < children.length; i++) {
  children[i].textContent = 'Updated text';
}

4.3 형제 요소의 스타일 변경

const currentElement = document.getElementById('current');
const nextElement = currentElement.nextElementSibling;

if (nextElement) {
  nextElement.style.color = 'red';
}

5. 노드 간 트래버설 예제

5.1 모든 자식 요소 순회

const parentNode = document.getElementById('parent');
const childNodes = parentNode.childNodes;

childNodes.forEach(node => {
  if (node.nodeType === Node.ELEMENT_NODE) {
    console.log(node);
  }
});

5.2 특정 조건에 맞는 요소 찾기

function findElementByTextContent(parent, text) {
  const elements = parent.getElementsByTagName('*');
  for (let element of elements) {
    if (element.textContent.includes(text)) {
      return element;
    }
  }
  return null;
}

const parentNode = document.getElementById('parent');
const foundElement = findElementByTextContent(parentNode, 'search text');
console.log(foundElement);

결론

자바스크립트의 DOM 트래버설은 웹 페이지의 요소를 탐색하고 조작하는 데 중요한 기술입니다. 다양한 속성 및 메서드를 사용하여 부모, 자식, 형제 노드 간의 관계를 탐색하고, 특정 요소를 선택하여 원하는 조작을 수행할 수 있습니다. DOM 트래버설을 잘 이해하고 활용하면 복잡한 DOM 구조에서도 효율적으로 작업할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *