DOM 탐색

Frontend SELF KO
레벨 41 , 레슨 1
사용 가능

2.1 요소에 접근하는 방법들

DOM(Document Object Model) 탐색은 웹 문서 작업에 있어 중요한 과제야. JavaScript는 문서의 요소를 찾고 접근할 수 있는 다양한 방법을 제공해. 이러한 방법들은 개발자가 필요한 요소를 쉽게 찾고 조작할 수 있게 도와줘.

1. getElementById() 메서드

getElementById() 메서드는 특정 값의 id 속성을 가진 요소를 반환해. 가장 간단하고 자주 사용되는 방법 중 하나야.

예시:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <div id="content">This is the content</div>

          <script>
            const contentDiv = document.getElementById('content');
            console.log(contentDiv.textContent); // 출력: This is the content
          </script>
        </body>
      </html>
    
  

2. getElementsByClassName() 메서드

getElementsByClassName() 메서드는 주어진 클래스를 가진 모든 요소의 컬렉션을 반환해. 컬렉션은 "라이브"라서 DOM이 변경될 때 자동으로 갱신돼.

예시:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <p class="text">Paragraph 1</p>
          <p class="text">Paragraph 2</p>
          <p class="text">Paragraph 3</p>

          <script>
            const paragraphs = document.getElementsByClassName('text');
            console.log(paragraphs.length); // 출력: 3
          </script>
        </body>
      </html>
    
  

3. getElementsByTagName() 메서드

getElementsByTagName() 메서드는 주어진 태그의 모든 요소의 컬렉션을 반환해. 이 컬렉션도 역시 "라이브" 컬렉션이야.

예시:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <p>Paragraph 1</p>
          <p>Paragraph 2</p>
          <p>Paragraph 3</p>

          <script>
            const paragraphs = document.getElementsByTagName('p');
            console.log(paragraphs.length); // 출력: 3
          </script>
        </body>
      </html>
    
  

4. querySelector() 메서드

querySelector() 메서드는 주어진 CSS 선택자와 일치하는 첫 번째 요소를 반환해. 굉장히 강력하고 유연한 방법이야.

예시:

HTML
    
      <!DOCTYPE html>
      <html>
      <head>
        <title>Document</title>
      </head>
        <body>
          <div class="container">
            <p>Paragraph 1</p>
            <p class="highlight">Paragraph 2</p>
            <p>Paragraph 3</p>
          </div>

          <script>
            const highlightedParagraph = document.querySelector('.highlight');
            console.log(highlightedParagraph.textContent); // 출력: Paragraph 2
          </script>
        </body>
      </html>
    
  

5. querySelectorAll() 메서드

querySelectorAll() 메서드는 주어진 CSS 선택자와 일치하는 모든 요소의 정적(변경되지 않는) 컬렉션을 반환해.

예시:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <div class="container">
            <p>Paragraph 1</p>
            <p class="highlight">Paragraph 2</p>
            <p>Paragraph 3</p>
          </div>

          <script>
            const paragraphs = document.querySelectorAll('.container p');
            console.log(paragraphs.length); // 출력: 3
          </script>
        </body>
      </html>
    
  

2.2 노드 탐색

DOM은 현재 요소를 기준으로 노드를 탐색할 수 있는 방법도 제공해.

1. parentNode 속성

parentNode 속성은 현재 노드의 부모 노드를 반환해.

예시:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <div id="container">
            <p>Paragraph</p>
          </div>

          <script>
            const paragraph = document.querySelector('p');
            const parent = paragraph.parentNode;
            console.log(parent.id); // 출력: container
          </script>
        </body>
      </html>
    
  

2. childNodes 속성

childNodes 속성은 현재 노드의 모든 자식 노드(텍스트 노드 포함) 컬렉션을 반환해.

예시:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <ul id="list">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
          </ul>

          <script>
            const list = document.getElementById('list');
            const children = list.childNodes;
            console.log(children.length); // 텍스트 노드 포함 모든 자식 노드 수를 출력
          </script>
        </body>
      </html>
    
  

왜 결과가 7인지 여전히 궁금할 수도 있어?

childNodes 속성은 현재 노드의 모든 자식 노드, 텍스트 노드(공백, 문자, 새 줄 등)를 포함하는 컬렉션을 반환한다고 앞서 언급했어. HTML 마크업은 <li> 요소 사이의 공백 및 새 줄도 개별 노드로 간주돼.

위 예시에서 <ul> 태그와 첫 번째 <li> 사이에 새 줄(그리고 아마도 공백)이 있어. 이게 텍스트 노드로 간주돼. 모든 <li> 사이와 마지막 <li> 뒤에도 같은 상황이 있어. 그래서 세 개의 리스트 요소 대신, childNodes는 이 텍스트 노드를 포함해서 총 7개의 노드를 포함하고 있어.

요소만 얻고 싶다면 children 속성을 사용하면 되는데, 이건 자식 요소만 반환해:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <ul id="list">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
          </ul>

          <script>
            const list = document.getElementById('list');
            const children = list.children;
            console.log(children.length); // 3
          </script>
        </body>
      </html>
    
  

3. firstChild와 lastChild 속성

firstChildlastChild 속성은 각각 첫 번째와 마지막 자식 노드를 반환해.

예시:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <ul id="list">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
          </ul>

          <script>
            const list = document.getElementById('list');
            const first = list.firstChild;
            const last = list.lastChild;
            console.log(first.textContent);
            console.log(last.textContent);
          </script>
        </body>
      </html>
    
  

콘솔에 아무것도 출력되지 않았을지도 몰라서 놀랐을지도 몰라. 실제로는 그렇지 않아. 첫 번째 자식 항목 Item 1과 마지막 자식 항목 Item 3 (새 줄)이 출력됐어. 이 단계에서 멈췄다면 2번 항목: childNodes 속성를 다시 읽어봐.

4. nextSibling와 previousSibling 속성

nextSiblingpreviousSibling 속성은 같은 레벨에서 다음과 이전 노드를 반환해.

예시:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <ul id="list">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
          </ul>

          <script>
            const secondItem = document.querySelector('li:nth-child(2)');
            const next = secondItem.nextSibling;
            const prev = secondItem.previousSibling;
            console.log(next.textContent); // 출력: Item 3
            console.log(prev.textContent); // 출력: Item 1 (텍스트 노드 생략 시)
          </script>
        </body>
      </html>
    
  

2.3 요소 노드 탐색

5. nextElementSibling와 previousElementSibling 속성

이 속성들은 다음과 이전 요소 노드를 반환해(텍스트와 코멘트를 건너뛰어).

예시:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <ul id="list">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
          </ul>

          <script>
            const secondItem = document.querySelector('li:nth-child(2)');
            const next = secondItem.nextElementSibling;
            const prev = secondItem.previousElementSibling;
            console.log(next.textContent); // 출력: Item 3
            console.log(prev.textContent); // 출력: Item 1
          </script>
        </body>
      </html>
    
  

6. firstElementChild와 lastElementChild 속성

이 속성들은 첫 번째와 마지막 자식 요소 노드를 반환해(텍스트와 코멘트를 건너뛰어).

예시:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <ul id="list">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
          </ul>

          <script>
            const list = document.getElementById('list');
            const first = list.firstElementChild;
            const last = list.lastElementChild;
            console.log(first.textContent); // 출력: Item 1
            console.log(last.textContent);  // 출력: Item 3
          </script>
        </body>
      </html>
    
  
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION