Document Object Model (DOM) is a platform and language-neutral interface which is used by programs and scripts to dynamically access the content, style and structure. Please refer to DOM (Document Object Model) to know the details. We can implement this by using DOM’s createElement(), createTextNode(), appendChild(), replaceChild() methods and childNodes property.
Let us discuss these methods and property to replace one HTML element to another.
- createElement(): It is used to create an element node with the specified name.
var element = document.createElement("Element_name");
In this example, the element is “h1” tag, so write
- createTextNode(): The method is used to create a text node.
var txt = document.createTextNode("Some_Text");
- appendChild(): After creating text node, we have to append it to the element by using appendChild() method.
The following shows the working code on how to use these methods and property discussed above.
- Before Clicking the Button:
- After Clicking the Button:
childNodes[Position]: This property returns a collection of child nodes as a NodeList object. The nodes are sorted as they appear in source code and can be accessed by index number starting from 0.
replaceChild(): It replace a child node with new node.
Example: The following code shows how to replace element with another one.
- Before clicking the Button:
- After clicking the Button: