We may want to add a new item to an HTML document. The first step is to create the node (element) that you want to add, the next step is to find the location in the document where you want to add it, and the last step is to do so. The syntax used to create a node is very simple, you only call a method (method) of the document object.
- createElement(): Creates a node of the specified name.
- createTextNode: allows you to add text to the node you specify.
- appendChild(): allows you to set where you want to node.
- insertBefore(): Used to add / move an existing item.
- removeChild(): removes a specified child node of the specified item.
- replaceChild():replaces a child node of the specified node with another node.
- cloneNode(): creates a copy of a node, and returns the copy.
- adoptNode(): This method is used to accept a node in another document.
- hasChildNodes():Returns true if the specified node has a child node. Returns a false node if the specified node does not have a child node.
- importNode(): This method imports another node from a document.
HTML DOM removeChild() Method
The removeChild () method removes a specified child node of the specified item. Returns the removed node as a Node object, or returns null if the node does not exist.
The removed child node still exists in memory, but the child node removed is no longer part of the DOM. However, it is possible to add the removed child to a member later with the reference returned by this method.
Syntax:
node.replaceChild (new, will change)
removeChild Examples
Example 1
<div class="container">
<p id="web">truecodes.org</p>
</div>
<button onclick="removeFunction()">remove</button>
<script>
function removeFunction() {
let cont = document.querySelector(".container");
let web = document.getElementById("web");
cont.removeChild(web)
}
</script>
Example 2
<body>
<ul class="animal">
<li>cat</li>
<li>dog</li>
<li>horse</li>
<li>chicken</li>
<li>cow</li>
</ul>
<button onclick="removeFunction()">remove</button>
<script>
function removeFunction() {
let ani = document.querySelector(".animal");
ani.removeChild(ani.childNodes[0]);
}
</script>
</body>