HTML DOM elements
Add, delete and replace HTML elements.
Create a new HTML element - appendChild ()
To add a new element to the HTML DOM, you must first create the element and append it to the existing elements.
Examples
<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.");
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChild(para);
</script>
try it"
Examples of analytical
This code creates a new <p> element:
To add text to the <p> element, you must first create a text node. This code creates a text node:
Then you must append text node to the <p> element:
Finally, you must add this new element to the existing elements.
Find this code to an existing element:
The code to add a new element to the existing elements:
Create a new HTML element - insertBefore ()
On one example of appendChild () method, the new element as the parent element's last child element to add.
If you do not want this, you can use the insertBefore () method:
Examples
<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.");
para.appendChild(node);
var element=document.getElementById("div1");
var child=document.getElementById("p1");
element.insertBefore(para,child);
</script>
try it"
Remove the existing HTML elements
To delete HTML elements, you must know the parent element of the element:
Examples
<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");
parent.removeChild(child);
</script>
try it"
Examples of analytical
This document contains HTML <div> element in one of the two child nodes (two <p> element) with the:
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
Find id = "div1" elements:
Find id = "p1" the <p> element:
Remove from the parent element sub-elements:
Can I delete an element in the case does not refer to the parent element? very sorry. DOM need to understand the elements that you want to delete, as well as its parent element. |
Here are a common solution: to find sub-elements you need to remove, and then use parentNode attribute to find its parent element:
child.parentNode.removeChild(child);
Replace HTML elements
To replace the HTML DOM elements, use replaceChild () method:
Examples
<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.");
para.appendChild(node);
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.replaceChild(para,child);
</script>
try it"