| Refresh | Home EGTry.com

create html content with dom api


commentsJavascript sourceExecution result in your current browser
create a text node and place inside another node
document.write("<div id='d1'></div>");
var mydiv=document.getElementById("d1");
var textNode=document.createTextNode("Hello"); 
mydiv.appendChild(textNode); 

create a real node
document.write("<div id='d2'></div>");
var div2=document.getElementById("d2");
var b=document.createElement("b"); 
var msg=document.createTextNode("Hello");
b.appendChild(msg);

div2.appendChild(b);

/** content:
<div id="d2">
<b>Hello</b>
</div>

*/

create an attribute
document.write("<div id='d3'></div>");
var div3=document.getElementById("d3");
var a=document.createElement("a");
var href=document.createAttribute("href"); 
href.nodeValue="http://www.egtry.com";
a.setAttributeNode(href);
var text=document.createTextNode("egtry.com");
a.appendChild(text);
div3.appendChild(a);
/** html content generated would be
<a href="http://www.egtry.com">egtry.com</a>

**/