Creating & removing HTML Elements (Nodes)
Creating:
<div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var element = document.getElementById("div1"); element.appendChild(para); </script>
<div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var element = document.getElementById("div1"); var child = document.getElementById("p1"); element.insertBefore(para, child); </script>
// Doesn't work in IE <div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var parent = document.getElementById("div1"); var child = document.getElementById("p1"); parent.removeChild(child); </script>
<div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var parent = document.getElementById("div1"); var child = document.getElementById("p1"); parent.replaceChild(para, child); </script>
Removing:
<!--Sample HTML code--> <div id="top"> <div id="nested"></div> </div> // Removing a specified element when knowing its parent node var d = document.getElementById("top"); var d_nested = document.getElementById("nested"); var throwawayNode = d.removeChild(d_nested); // Removing a specified element without having to specify its parent node var node = document.getElementById("nested"); if (node.parentNode) { node.parentNode.removeChild(node); } // Removing all children from an element var element = document.getElementById("top"); while (element.firstChild) { element.removeChild(element.firstChild); }