May 09, 2021 HTML DOM
2. Create a new HTML element - appendChild()
4. Create a new HTML element - insertBefore()
In this section, you'll learn how to add, remove, and replace HTML elements.
If you need to add a new element to html DOM, you must first create the element and then append it to an existing element.
This code creates a new element:
To add text to the element, you must first create a text node. This code creates a text node:
Then you must append the text node to the element:
Finally, you must append the new element to the existing element.
This code finds an existing element:
This code appends a new element to this existing element:
After reading the above instance analysis, you'd better be able to look at the instance again and do it!
In the appendChild() method in the last example, the new element is added as the last child element of the parent element.
If you don't want to, you can use the insertBefore() method:
If you need to remove an HTML element, you must be aware of the element's parent element, click Try:
<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>
This HTML document contains an element with two child nodes (two .
Find the element of id"div1":
Find the element of the id="p1":
Remove child elements from the parent element:
After reading the above instance analysis, you'd better be able to look at the instance again and do it!
Can I delete an element without referencing the parent element?
I'm so sorry. The DOM needs to understand the element that you need to remove, and its parent element. |
Here's a common workaround: find the child element you need to delete, and then use the parentNode property to find its parent element:
If you need to replace elements in HTML DOM, use the replaceChild() method: