To add a new element to the HTML DOM, you must create the element first, and then append it to an existing element. Here is an example:
Letβs take a moment to see whats going on inside this example code snippet. As seen, we first created a <p> node, and since the text inside of it is needed to be in a textNode, we then create a text node with the desired text inside. Then we append the text node as a child node to the paragraph node. Markup languages like HTML, are all trees.
If I wanted to then add, say an attribute, to the paragraph node, I would do something like this:
Creating new HTML Elements - insertBefore()
Previously, the appendChild() method appends the new element as the last child of the parent. If we want the element to be appended as the first child, we can use the insertBefore() method.
Removing Existing HTML Elements
To remove an HTML element, we use the remove() method:
*NOTE: ** remove() does not work in older browsers, instead, on older versions, we would use removeChild().
Removing a child node
Example:
The removeChild() method is from the parent node object. If your unsure what the parent node is, we can simply get the parent node of the child node through a method of the child node:
Replacing HTML elements
In order to replace an element in the HTML DOM, we use the replaceChild() method. Consider the following code: