HTML DOM - Elements
Add, delete, and replace HTML elements.
Creating New HTML Elements - createElement()
To add a new element to the HTML DOM, you must first create the element and then append it to an existing element.
Example
Try it Yourself »
Example Explained
This code creates a new <p> element:
To add text to the <p> element, you must first create a text node. This code creates the text node:
Then you must append the text node to the <p> element:
Finally, you must append the new element to an existing element.
This code finds an existing element:
This code appends the new element to the existing element:
Creating New HTML Elements - insertBefore()
In the previous example, the appendChild() method added the new element as the last child of the parent element.
If you don't want that, you can use the insertBefore() method:
Example
Try it Yourself »
Deleting Existing HTML Elements
To delete an HTML element, you must know the parent element of that element:
Example
Try it Yourself »
Example Explained
This HTML document contains a <div> element with two child nodes (two <p> elements):
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
Find the element with id="div1":
Find the <p> element with id="p1":
Delete the child element from the parent element:
| Can we delete an element without referencing its parent? Sorry. The DOM needs to know the element you want to delete and its parent. |
Here is a common workaround: Find the child element you want to delete, and then use the parentNode property to find its parent:
child.parentNode.removeChild(child);
Replacing HTML Elements
To replace an element in the HTML DOM, use the replaceChild() method:
Example
Try it Yourself »