Add and remove nodes (HTML elements).
Create a new HTML element
To add a new element to the HTML DOM, you must first create the element (the element node), and then append the element to an existing element.
Instance
<div id= "Div1" ><p id= "P1" > This is a paragraph </p><p id= "P2" > This is another paragraph </p></div><script >var para=document.createelement ("P"); var Node=document.createtextnode ("This is a new paragraph. ");p ara.appendchild (node), Var Element=document.getelementbyid (" Div1 "); Element.appendchild (para);</script>
Example Explanation:
This code creates a new <p> element:
var para=document.createelement ("P");
To add text to the <p> element, you must first create a text node. This piece of code creates a text node:
var Node=document.createtextnode ("This is the new paragraph. ");
Then you must append the text node to the <p> element:
Para.appendchild (node);
Finally, you must append this new element to an existing element.
This code finds an existing element:
var Element=document.getelementbyid ("Div1");
This code appends a new element to the existing element:
Element.appendchild (para);
Delete an existing HTML element
To delete an HTML element, you must first obtain the parent element of the element:
<div id= "Div1" ><p id= "P1" > This is a paragraph. </p><p id= "P2" > this is another paragraph. </p></div><script>var Parent=document.getelementbyid ("Div1"); var Child=document.getelementbyid ("P1");p arent.removechild (child);</script>
JS node operation