HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
Add, delete and replace HTML elements.
To add a new element to the HTML DOM, you must first create the element and append it to the existing elements.
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:
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:
To delete HTML elements, you must know the parent element of the element:
<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>
This document contains HTML <div> element in one of the two child nodes (two <p> element) with the:
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:
To replace the HTML DOM elements, use replaceChild () method: