8.3 Selecting Parent, Child and Sibling nodes
Next, let’s learn how to access an element based on its relationship with other nodes.
Add the following HTML code to DOMProperties.html (just after the <body> opening tag):
<ul> <li>A</li> <li>B</li> <li>C</li> </ul>
This code adds an unordered list to your webpage.
The diagram below shows the DOM diagram of this <ul> node.
8.3.1 childNodes.length
As you can see from the DOM diagram, the <ul> node has 7 child nodes. You can verify that using the childNodes.length property. Add
console.log(document.querySelector("ul").childNodes.length);
to chap8.js and refresh your browser. You’ll see 7 as the output in the console window.
8.3.2 firstChild and lastChild
You can access the first child and last child of an element using the firstChild and lastChild properties respectively. Add
document.querySelector("ul").firstChild.textContent = "First Child Changed"; document.querySelector("ul").lastChild.textContent = "Last Child Changed";
to chap8.js. You’ll get the following output in the browser:
The text content of the first and last child nodes have been changed.
8.3.3 childNodes[ ]
We can also access other child nodes of the element. Child nodes of an element are stored as an array. To access them individually, we use their indexes.
Add the following line to chap8.js.
document.querySelector("ul").childNodes[3].style.backgroundColor = "Green";
You’ll see the background color of the second item in the unordered list change to green.
In the Javascript statement above, we first use
document.querySelector("ul")
to select the <ul> element.
Next, we use the childNodes[3] property to get the fourth child node, which corresponds to the second item in the list (denoted by ^ in the DOM diagram).
Finally, we use style.backgroundColor to change the background color to green.
8.3.4 previousSibling and nextSibling
To access a sibling node that comes immediately before a particular node, we use the previousSibling property.
To access the sibling immediately after it, we use the nextSibling property.
Try adding the following lines to chap8.js.
document.querySelector("ul").childNodes[3].previousSibling.textContent = "Previous Sibling"; document.querySelector("ul").childNodes[3].nextSibling.textContent = "Next Sibling";
You’ll get the following output.
8.3.5 parentNode
Last but not least, if we want to access the parent node of an element, we use the parentNode property. Add
document.querySelector("ul").parentNode.style.backgroundColor = "Red";
to chap8.js. You’ll see the background color of the page change to red. This is because the parent node of the <ul> element is the <body> element. The background color of the <body> element is essentially the background color of the entire page.