HTML DOM 탐색



HTML DOM을 사용하면 노드 관계를 사용하여 노드 트리에서 탐색할 수 있습니다.


HTML DOM 노드 목록

getElementsByTagName() 메서드는 노드 목록을 반환합니다. 노드 목록은 노드의 배열입니다.

다음 코드는 문서의 모든 <p> 노드를 선택합니다.

Instance

<html><!DOCTYPE html>
<html>
<body>

<p>Hello World!</p>
<p>The DOM is very useful!</p>

<script>
x=document.getElementsByTagName("p");
document.write("The innerHTML of the second paragraph is: " + x[1].innerHTML);
</script>

</body>
</html>

Run Instance»

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 클릭하세요

참고:

다음 라벨은 0부터 시작합니다.


HTML DOM 노드 목록 길이

길이 속성은 노드 목록의 노드 수를 정의합니다.

길이 속성을 사용하여 노드 목록을 반복할 수 있습니다.

Instances

<html><!DOCTYPE html>
<html>
<body>

<p>Hello World!</p>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>length</b> property.</p>

<script>
x=document.getElementsByTagName("p");
for (i=0;i<x.length;i++)
  { 
  document.write(x[i].innerHTML);
  document.write("<br>");
  }
</script>
</body>
</html>

Run Instance»

온라인 인스턴스를 보려면 "Run Instance" 버튼을 클릭하세요

인스턴스 분석:

  • 모든<p> 요소 노드 가져오기

  • 각 <p> 요소의 텍스트 노드 값 출력


Navigation 노드 관계

parentNode, firstChild 및 lastChild, 문서 구조 탐색에서.

아래 HTML 스니펫을 참조하세요.

<html>
<body>

<p>Hello World!</p>
<div>
<p>DOM은 매우 유용합니다!</p>
<p>이 예는 노드 관계를 보여줍니다.</p>
</div>

</body>
</html>
  • 첫 번째 <p> 요소는 <body> ; 요소의 첫 번째 하위 요소(firstChild)

  • <div> 요소는 <body> 요소의 마지막 하위 요소(lastChild)입니다.

  • <body> <div> 요소의 상위 노드(parentNode)

firstChild 속성을 사용하여 요소의 텍스트에 액세스할 수 있습니다:

Instance

<html><!DOCTYPE html>
<html>
<body>

<p id="intro">Hello World!</p>

<script>
x=document.getElementById("intro");
document.write(x.firstChild.nodeValue);
</script>

</body>
</html>

인스턴스 실행»

보려면 "인스턴스 실행" 버튼을 클릭하세요. 온라인 인스턴스


DOM 루트 노드

여기에는 모든 문서에 액세스할 수 있는 두 가지 특수 속성이 있습니다:

  • document.documentElement - 모든 문서

  • document.body - 문서 본문

인스턴스

<html><!DOCTYPE html>
<html>
<body>

<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>

<script>
alert(document.body.innerHTML);
</script>

</body>
</html>

인스턴스 실행»

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 클릭하세요


childNodes 및 nodeValue

innerHTML 속성 외에도 childNodes 및 nodeValue 속성을 사용하여 요소의 콘텐츠를 가져올 수도 있습니다.

다음 코드는 id="intro"를 사용하여 <p> 요소의 값을 가져옵니다.

Instance

<html><!DOCTYPE html>
<html>
<body>

<p id="intro">Hello World!</p>

<script>
txt=document.getElementById("intro").childNodes[0].nodeValue;
document.write(txt);
</script>

</body>
</html>

Run Instance»

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 클릭하세요.

위의 예에서 getElementById는 메소드이고 childNodes 및 nodeValue는 속성입니다.

이 튜토리얼에서는 innerHTML 속성을 사용합니다. 하지만 위의 방법을 배우면 DOM 트리 구조와 탐색을 이해하는 데 도움이 됩니다.