XML DOM lastChild 속성

정의와 사용법

lastChild 지정된 노드의 마지막 자식 노드를 반환하는 속성입니다.

문법

nodeObject.lastChild
팁과 주의사항

주의: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_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);
    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_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);
    // 언어의 첫 번째 자식 노드를 가져옵니다.
    var y = get_firstchild(xmlDoc.documentElement);
    document.getElementById("demo").innerHTML =
    "Nodename: " + x.nodeName +" 
    " (nodetype: " + x.nodeType + ")<br>" +
    "Nodename: " + y.nodeName + 
    " (nodetype: " + y.nodeType + ")<br>";
}

직접 시도해보세요