DOM, Node propertity and Method

W3C의 Document Object Model 표준은 문서의 엘리먼트를 노트 컬렉션으로 구성하고, 이들을 트리 계층구조로 연결을 하였다. 파이어폭스에서 DOM Inspector를 실행해 페이지의 객체의 구조를 살펴 볼 수 있다. DOM Inspector는 부가 기능으로 설치할 수 있다.

https://addons.mozilla.org/ko/firefox/addon/6622

아래의 자바 스크립트 코드를 이용하면 DOM 구조에서 노드의 위치와 그 노드가 가지는 값들을 알 수 있다.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>The Node</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
//<![CDATA[
function randomColor(){
    r = Math.floor(Math.random() * 255).toString(16);
    g = Math.floor(Math.random() * 255).toString(16);
    b = Math.floor(Math.random() * 255).toString(16);
    return "#" + r + g + b;
}

// Print Node some properties.
function outputNodeProps(nd){
    var strNode = "Node Type: " + nd.nodeType;
    strNode += "\nNode Name: " + nd.nodeName;
    strNode += "\nNode Value: " + nd.nodeValue;

    // execute if node was set
    if(nd.style){
        var clr = randomColor();
        nd.style.backgroundColor = clr;
        strNode += "\nbackgroundColor: " + clr;
    }

    // print
    alert(strNode);

    var children = nd.childNodes;
    for(var i=0; i < children.length; i++){
        outputNodeProps(children[i]);
    }
}
//]]>
</script>
</head>

<body onload="outputNodeProps(document);">
<div id="div1">
<h1>Header</h1>
<!-- paragraph one -->
<p>To better understand the document tree, consider a web page that has a head and body section, has a page title, and contains a DIV element that itself contains and H1 header and two paragraphs. One of the paragraphs contains <i>italicized text</i>; the other has an image--not an uncommon web page.</p>

<!-- paragraph two -->
<p>Second paragraph with image following.</p>
<p>[IMAGE]</p>
</div>

</body>
</html>

이 코드는 “자바스크립트 for Web2.0”에서 발췌하였습니다.

아래의 이미지는 위 코드 자체가 가지는 DOM 구조이다.

 
▲ DOM Inspector

 

 
▲ 코드 실행 결과 중 하나

참고 : Document Object Model (DOM) Level 2 Core Specification

댓글 쓰기