XML DOM firstChild 속성
정의 및 사용법
firstChild
지정된 노드의 첫 번째 자식 노드를 반환하는 속성입니다.
문법
nodeObject.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>"; }