JavaScript Node Methods

appendChild()

  1. Appends a child node to the end of the list of children of the given node.
<div id="myDiv"></div>
const paragraph = document.createElement("p");
paragraph.textContent = "This is a paragraph.";
document.getElementById("myDiv").appendChild(paragraph);

This will create a new p element with the text "This is a paragraph." and append it to the div element with the ID myDiv.

cloneNode()

  1. Creates a copy of the given node.
<div id="myDiv">
    <p>This is a paragraph.</p>
</div>
  
const clonedParagraph = document.getElementById("myDiv").firstElementChild.cloneNode(true);
document.getElementById("myDiv").appendChild(clonedParagraph);

This will create a copy of the first child element of the div element with the ID myDiv and append it to the same div element.

hasChildNodes()

  1. Returns a Boolean value indicating whether the given node has any child nodes.
<div id="myDiv"></div>
const hasChildNodes = document.getElementById("myDiv").hasChildNodes();
console.log(hasChildNodes); // false

This will check whether the div element with the ID myDiv has any child nodes and return a Boolean value (true if it has child nodes, false otherwise).

insertBefore()

  1. Inserts a child node before the given child node of the given parent node.
<div id="myDiv">
    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>
</div>
  
const newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
document.getElementById("myDiv").insertBefore(newParagraph, document.getElementById("myDiv").lastElementChild);

This will create a new p element with the text "This is a new paragraph." and insert it before the last child element of the div element with the ID myDiv.

removeChild()

  1. Removes a child node from the list of children of the given parent node.
<div id="myDiv">
    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>
</div>
  
document.getElementById("myDiv").removeChild(document.getElementById("myDiv").firstElementChild);

This will remove the first child element of the div element with the ID myDiv.

replaceChild()

  1. Replaces a child node with another child node.
<div id="myDiv">
    <p>This is the first paragraph.</p>
</div>
  
const newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
document.getElementById("myDiv").replaceChild(newParagraph, document.getElementById("myDiv").firstElementChild);

This will replace the first child element of the div element with the ID myDiv with the new p element created above.