DOM Manipulation with Pure JS
How to create elements on the fly and append to parent elements.
by queryj
HTML
<div>
some content goes here.
</div>
<p>
just a paragraph.
</p>
<p>
anothr paragraph.
</p>
<span>
</span>
<table id="table1">
<caption>just a table.</caption>
</table>
CSS
p {
background-color: green;
}
.para
{
font-weight: bold;
color: white;
}
table, tr, td{
width: 100%;
border: 1px solid gray;
border-collapse: collapse;
}
caption{
border: 3px dotted red;
}
JavaScript
document.getElementsByTagName("p")[1].style.background = "orange";
document.getElementsByTagName("div")[0].innerHTML = "yeah, there you go.";
var div = document.createElement("div");
div.innerHTML = "created on the fly";
div.style.border = "1px solid red";
div.style.marginTop="40px";
var p = document.createElement("p");
p.innerHTML = "a paragraph created on the fly and will be inserted into the new div";
p.style.margin = "5px 5px 2px 5px";
p.style.padding = "8px";
p.setAttribute("id", "pppp");
p.setAttribute("class", "para");
div.appendChild(p);
var inp = document.createElement("input");
inp.setAttribute("type", "text");
p.appendChild(inp);
var sel = document.createElement("select");
var o = document.createElement("option");
o.setAttribute("value", "first");
o.innerHTML = "di yi ge";
var o1 = document.createElement("option");
o1.setAttribute("value", "second");
o1.innerHTML = "di er ge";
sel.appendChild(o);
sel.appendChild(o1);
document.body.appendChild(div);
document.body.appendChild(sel);
var len = document.body.childNodes.length;
document.getElementsByTagName("span")[0].innerHTML = "len is " + len;
console.log(document.body.childNodes[9]);
//console.log(document.childNodes[1]);
//remove span
var span = document.getElementsByTagName("span")[0];
document.body.removeChild(span);
//insert after the first p
var newNode = document.createElement("p");
newNode.innerHTML = "inserted after the 1st p of the dom.";
var p1 = document.getElementsByTagName("p")[0];
p1.parentNode.insertBefore(newNode, p1.nextSibling);
var p2 = document.getElementsByTagName("p")[1];
//p2.parentNode.insertBefore(newNode, p2.previousSibling);
var ss = document.styleSheets;
console.log(ss.length);
for(var i = 0; i < ss.length; i++) {
for(var j = 0; j < ss[i].cssRules.length; j++) {
console.log( ss[i].cssRules[j].selectorText + "\n" );
}
}
var table = document.getElementById("table1");
var row = table.insertRow(-1);
var c1 =...