XML DOM firstChild 속성
정의와 사용법
firstChild
속성은 문서의 첫 번째 자식 노드를 반환합니다.
문법
documentObject.firstChild주의:Firefox와 대부분의 다른 브라우저는 공백이나 개행을 텍스트 노드로 간주하지만, Internet Explorer는 그렇지 않습니다. 따라서 아래의 예제에서는 첫 번째 자식 노드의 노드 타입을 확인하는 함수를 사용합니다.
요소 노드의 nodeType는 1이므로 첫 번째 자식 노드가 요소 노드가 아니면 다음 노드로 이동하여 요소 노드인지 확인합니다. 이 과정은 첫 번째 자식 노드(요소 노드여야 합니다)를 찾을 때까지 반복됩니다. 이렇게 하면 모든 브라우저에서 결과가 일관됩니다。
ヒント:브라우저 간의 차이에 대해 더 많은 정보를 얻으려면 XML DOM 튜토리얼의 DOM 브라우저 장을 방문하세요.
예제
예제 1
아래 코드는 "books.xml"을 xmlDoc에 로드하고, 첫 번째 자식 노드의 노드 이름과 노드 유형을 표시합니다:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); // 첫 번째 노드가 요소 노드인지 확인합니다 function get_firstchild(n) { var x = n.firstChild; while (x.nodeType != 1) { x = x.nextSibling; } return x; } function myFunction(xml) { var xmlDoc = xml.responseXML; var x = get_firstchild(xmlDoc); document.getElementById("demo").innerHTML = "Nodename: " + x.nodeName +" " (nodetype: " + x.nodeType + ")<br>"; }
예제 2
문서의 최종 자식 노드를 가져옵니다:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); // 마지막 노드가 요소 노드인지 확인합니다 function get_lastchild(n) { var x = n.lastChild; while (x.nodeType != 1) { x = x.previousSibling; } return x; } function myFunction(xml) { var xmlDoc = xml.responseXML; // 문서의 최종 자식 노드를 가져옵니다 var x = get_lastchild(xmlDoc); // 각각의 최종 자식 노드를 가져옵니다 var y = get_lastchild(xmlDoc.documentElement); document.getElementById("demo").innerHTML = "Nodename: " + x.nodeName +" " (nodetype: " + x.nodeType + ")<br>" + "Nodename: " + y.nodeName + " (nodetype: " + y.nodeType + ")<br>"; }