[JavaScript] firstChild와 nextSibling
↓↓↓ DOM 개념 알아보기 ↓↓↓
https://yyyeji.tistory.com/160
[JavaScript] DOM이란?
DOM 이란? Document object Model의 줄임말로써, XML 문서의 메모리 내 표현이고 DOM을 사용하여 XML 문서를 프로그래밍 방식으로 element를 생성, 조회, 갱신, 삭제할 수 있습니다. Method 생성 - document.createElem
yyyeji.tistory.com
firstChild는
현재 요소(element)의 첫 번째 child node를 반환하고,
nextSibling은
현재 요소(element) child node의 다음 child node를 반환합니다.
W3School에 나오는 Books.xml을 살펴보겠습니다.
<bookstore>
<book category="cooking">
<title lang ="en"> Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang = 'en'> Harry Potter </title>
<author>J K.Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang = 'en'> XQuery Kick Start </title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang = 'en'> Learning XML </title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
↑↑↑ Books.xml ↑↑↑
function myFunction(xml) {
var x, y, i, xlen, xmlDoc, txt;
xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("book")[0];
xlen = x.childNodes.length;
y = x.firstChild;
txt = "";
for (i = 0; i<xlen; i++) {
if(y.nodeType == 1) {
txt += i + " " + y.nodeName + "<br>";
}
y = y.nextSibling;
}
document.getElementById("demo").innerHTML = txt;
}
↑↑↑ h.html ↑↑↑
천천히 살펴보겠습니다.
x = xmlDoc.getElementsByTagName("book")[0];
→ 'book'이라는 이름을 가진 여러 개의 tag 중 1번째 node를 반환합니다.
xlen = x.childnodes.length;
→ 현재 x에는 첫 번째 book tag가 반환되어 있습니다.
→ childnodes는 book tag의 childnode를 의미합니다.
→ length는 book tag의 childnode의 개수를 반환합니다.
y = x.firstChild;
→ 현재 x에는 첫 번째 book tag가 반환되어 있고,
→ book tag의 첫 번째 child node를 반환합니다.
조건문의 의미를 알고 싶다면 아래 링크를 따라가주세요!
txt += i + " " + y.nodeName + "<br>";
→ childNodes의 순서를 의미합니다.
txt += i + " " + y.nodeName + "<br>";
→ 공백을 넣어줍니다.
txt += i + " " + y.nodeName + "<br>";
→ 현재 y에는 book tag의 child node가 들어가 있고,
→ child node의 tag name을 반환합니다.
txt += i + " " + y.nodeName + "<br>";
→ 줄바꿈을 해줍니다.
y = y.nextSibling;
→ 현재 y에 있는 book tag child node의 다음 child node를 반환합니다.
x = xmlDoc.getElementsByTagName("book")[0];
y = x.firstChild;
txt = "";
for (i = 0; i<xlen; i++) {
if(y.nodeType == 1) {
txt += i + " " + y.nodeName + "<br>";
}
y = y.nextSibling;
}
여기서 first child를 바로 호출(invoke)할 수 있습니다.
x = xmlDoc.getElementsByTagName("book")[0];
y = x.firstChild;
x = xmlDoc.getElementsByTagName("book")[0].firstChild;
↓↓↓ 조건문이 궁금하다면? ↓↓↓
https://yyyeji.tistory.com/240
[JavaScript] nodeType이란
↓↓↓ DOM 개념 알아보기 ↓↓↓ https://yyyeji.tistory.com/160 [JavaScript] DOM이란? DOM 이란? Document object Model의 줄임말로써, XML 문서의 메모리 내 표현이고 DOM을 사용하여 XML 문서를 프로그래밍 방식으로
yyyeji.tistory.com
◡̈