Main content:
1. HTML DOM Elements
2. HTML DOM Events
3. HTML Dom Instance
First, DOM elements
Main operations include adding, deleting, and replacing HTML elements
1. Create a new HTML element
(1) Method one: AppendChild () append
To add a new element to the HTML DOM, you must first create the element and then append it to the existing element.
Examples and parsing:
<div id= "Box1" > <p id= "P1" >this are first paragraph.</p> <p id= "P1" >this is second paragraph. </p></div><script>//Create a new <p> element varPara = document.createelement ("P"); //To add text to the <p> element, you create the text node first, and the following sentence is the creation of the text node varnode = document.createTextNode ("This is new!"); //Next, you'll append the text node to the <p> elementpara.appendchild (node); //Finally, to append this element to an existing element, first find the element varelement = document.getElementById ("Box1"); //add a new element to an existing elementElement.appendchild (para); </script>
(2) Method two: InsertBefore (new,old) insert
Instance:
<div id= "Box1" ><p id= "P1" >this is a paragraph.</p><p id= "P2" >this is another paragraph.</p ></div><script>varPara = document.createelement ("P");//Create a new <p> elementvarnode = document.createTextNode ("This is another one!");//Create a text nodePara.appendchild (node);//Append text nodes to <p>varelement = document.getElementById ("box");//find the parent node of the <p> nodevarChild = document.getElementById ("P1");//find the sibling node of the <p> nodeElement.insertbefore (Para,child);//Insert the newly created <p> node before the sibling node with ID p1
2. Delete existing HTML elements
To delete an HTML element, you need to know the parent element of the element.
Instance:
<div id= "Box1" ><p id= "P1" >this is a paragraph.</p><p id= "P2" >this is another paragraph.</p ></div><script> // Gets the parent element var , parent = document.getElementById (" Box1 "); // get the element to delete var child = document.getElementById ("P1"); // Delete the element parent.removechild (child); </script>
Shorthand: Find the child element you want to delete, and then use the ParentNode property to find its parent element
var child = document.getElementById ("p1"// Child.parentnode represents the child's parent element
3. Replace HTML elements
To replace elements in the HTML DOM, use the ReplaceChild (New,old) method:
<div id= "Box1" > <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 new NEW!") ); Para.appendchild (node); var parent = document.getElementById ("Box1"); var child = document.getElementById ("P2"); Parent.replacechild (para,child); </script>
Not to be continued ...
Front-end development of JavaScript HTML DOM theory Chapter Two