We've looked at how to access the current elements on the DOM, so now let's learn how to create and delete them.
To create an element, use the
createElement() method, which takes in an element type. We then store this reference into a variable, and use the methods we learned in the previous lessons to add attributes and text nodes.
var newElement = document.createElement("p"); body.appendChild(newElement); body.newElement.removeChild(newElement);
To set attributes to our newly created element Now we can just set the ID.
We may also create a text node by using the
createTextNode() method. Simply attach this node to our element.
var myTextNode = document.createTextNode("text here"); newElement.appendChild(myTextNode);
To append the element to the DOM, we use the
appendChild() method. This takes in the variable that holds a reference to your newly created element. You can then attach it to any pre-exiting element.
To remove a node, simply use the
var elementRemoval = document.getElementById("removeMe"); document.body.removeChild(elementRemoval);
This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.$ Check price
This book teaches HTML as if it's for anyone - hobbyists, students, and professionals - and it's full-color throughout. It utilizes information graphics and lifestyle photography to explain the topics in a simple way that is engaging. You can progress through the chapters from beginning to end or just dip into topics of particular interest at your leisure.$ Check price