[JavaScript] Node 추가하고 교환하기
↓↓↓ DOM 개념 알아보기 ↓↓↓
https://yyyeji.tistory.com/160
[JavaScript] DOM이란?
DOM 이란? Document object Model의 줄임말로써, XML 문서의 메모리 내 표현이고 DOM을 사용하여 XML 문서를 프로그래밍 방식으로 element를 생성, 조회, 갱신, 삭제할 수 있습니다. Method 생성 - document.createElem
yyyeji.tistory.com
Node를 추가하고 싶을 땐 어떻게 할까요?
예제로 바로 들어가겠습니다.
<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, z, i, newNode, newTitle, newText, xmlDoc, txt;
xmlDoc = xml.responseXML;
txt = "";
x = xmlDoc.documentElement;
// Create a book element, title element and a text node
newNode = xmlDoc.createElement("book");
newTitle = xmlDoc.createElement("title");
newText = xmlDoc.createTextNode("A Notebook");
// Add a text node to the title node
newTitle.appendChild(newText);
// Add the title node to the book node
newNode.appendChild(newTitle);
y = xmlDoc.getElementsByTagName("book")[0];
// Replace the first book node with the new book node
x.replaceChild(newNode, y);
z = xmlDoc.getElementsByTagName("title");
// Output all titles
for (i = 0; i < z.length; i++) {
txt += z[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
newNode = xmlDoc.createElement("book");
→ Book node를 생성합니다.
newTitle = xmlDoc.createElement("title");
→ Title node를 생성합니다.
newText = xmlDoc.createTextNode("A NoteBook");
→ node의 text를 생성합니다.
newTitle.appendChild(newText);
→ title node에 text를 넣어줍니다.
newNode.appendChild(newTitle);
→ book node에 child node로 title node를 넣어줍니다.
y = xmlDoc.getElementBysTagName("book")[0];
→ Bookstore의 첫 번째 book node를 반환합니다.
x.replaceChild(newNode, y);
→ 새로 생성해준 node와 원래 있는 노드를 교환해줍니다.
newNode = xmlDoc.createElement("book");
newTitle = xmlDoc.createElement("title");
newText = xmlDoc.createTextNode("A Notebook");
newTitle.appendChild(newText);
newNode.appendChild(newTitle);
y = xmlDoc.getElementsByTagName("book")[0];
x.replaceChild(newNode, y);
◡̈