Locked lesson.
About this lesson
Adding new nodes on the fly with JavaScript.
Exercise files
Download this lesson’s related exercise files.
Creating New Nodes.docx59.1 KB Creating New Nodes - Solution.docx
59.7 KB
Quick reference
Creating New Nodes
Creating new nodes is a two-step process.
When to use
Any time you want to create a new node, use one of these two methods.
Instructions
To create a new node after another node, use .appendChild:
<div id="myDiv">
<p id="first">This is my text...</p>
</div>
<script>
var newP = document.createElement("p");
var newNode = document.createTextNode("This is new text!");
newp.appendChild(newNode);
var myElement = document.getElementById("myDiv");
myElement.appendChild(newp);
</script>
To create a new node and put it before another node, use .insertBefore:
<div id="myDiv">
<p id="first">This is my text...</p>
</div>
<script>
var newP = document.createElement("p");
var newNode = document.createTextNode("This is new text!");
newp.appendChild(newNode);
var myElement = document.getElementById("myDiv");
var myChild = document.getElementById("first");
myElement.insertBefore(newP, myChild);
</script>
Hints & tips
- Adding new nodes is just another way to manipulate HTML elements
- Adding new nodes is a two-step process
Lesson notes are only available for subscribers.