관리 메뉴

드럼치는 프로그래머

[JavaScript] createElement, 새로운 요소 생성하기. 본문

★─Programing/☆─WebProgram

[JavaScript] createElement, 새로운 요소 생성하기.

드럼치는한동이 2016. 7. 28. 09:24

from. http://www.zytrax.com/tech/dom/createelement.html

Example

// create a new paragraph
newpara = document.createElement("p");

// now some text
sometext = document.createTextNode("what a way to spend a life");

// add the text to the paragraph
newpara.appendChild(sometext);

// get an existing object and append them
existingobject = document.getElementById("one");
existingobject.appendChild(newpara);


Notes

createElement 는 단 한번 사용할 수 있는 단일 instance 요소를 생성한다.

// this code will NOT add two paragraphs with the same contents
// create a new paragraph
newpara = document.createElement("p");
// now some text
sometext = document.createTextNode("what a way to spend a life");
newpara.appendChild(sometext);
// stick the paragraph onto an existing object
obj1 = document.getElementById("one");
obj1.appendChild(newpara);
obj1.appendChild(newpara);

// this code WILL give desired results
// create a new paragraph
newpara = document.createElement("p");
// now some text
sometext = document.createTextNode("what a way to spend a life");
// append to paragraph
newpara.appendChild(sometext);
// stick the paragraph onto an existing object
obj1 = document.getElementById("one");
obj1.appendChild(newpara);
newpara = document.createElement("p"); // create new instance
sometext = document.createTextNode("what a way to spend a life");
newpara.appendChild(sometext);
obj1.appendChild(newpara);


요소를 생성한 뒤에는 HTML document 내의 무엇인가에 append 해야 한다.

// this code does NOT work
newdiv = document.createElement("div");
// set div attributes
newdiv.className = "x";
newdiv.id = "mine";
...
mydiv = document.getElementById("mine"); // does not find it

// this code DOES work
newdiv = document.createElement("div");
// set div attributes
newdiv.className = "x";
newdiv.id = "mine";
document.body.appendChild(newdiv); // or some other node
...
mydiv = document.getElementById("mine"); // finds it


[출처http://egloos.zum.com/mulriver/v/4696405


Comments