Node in JavaScript
JavaScript enables the convention to track HTML elements
parent and child nodes. Generally, if we have an element under another element, the overall structure for this pattern will be called the parent-child tree
.
In JavaScript, we can alter any child element of the parent element. Also, we can add and remove the children.
Here we will see two examples where one will explain how we can differentiate multiple types of children elements. The other example will depict appending a new child element to the parent element.
Pick the Child Node From a Parent Node in JavaScript
In this case, we will initiate a div
element having multiple p
elements and an article
element. The drive is to pick all the p
elements and color them in a different hue to differentiate on the article
and p
elements.
Let’s focus on the code lines for better understanding.
Code Snippet:
<!DOCTYPE html>
<html>
<body>
<p>Hello World!</p>
<article>
Howdy!
</article>
<p>Click button to change the color of all p elements.</p>
<button onclick="changeColor()">Hit it</button>
<script>
function changeColor() {
const Nodelist = document.querySelectorAll("p");
for (let i = 0; i < Nodelist.length; i++) {
Nodelist[i].style.color = "blue";
}
}
</script>
</body>
</html>
Output:
Append New Child Node to a Particular Parent Node in JavaScript
Here we will see an instance where we will append a new child node. We will have a div
element with multiple p
elements.
A new node will be added from the script tag. First, we will perform createElement
and create the p
tag.
Later we will add the text to the p
element. The next step will append this new node to the parent node, and this new node will be automatically added to the HTML preview
.
Code Snippet:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="div1">
<p>paragraph 1.</p>
<p>paragraph 2.</p>
</div>
<script>
const p = document.createElement("p");
const node = document.createTextNode("paragraph 3.");
p.appendChild(node);
const element = document.getElementById("div1");
element.appendChild(p);
</script>
</body>
</html>
Output: