Using childNodes in JavaScript DOM (Live Playground)
In this tutorial, we will learn how to use the childNodes
property in JavaScript to access and manipulate child elements of a given HTML element in the DOM. We'll cover the basics of the childNodes property and provide sample code with explanations.
What is childNodes?
The childNodes
property is a built-in JavaScript DOM property that allows you to access a live NodeList representing the child elements of a given HTML element in the DOM hierarchy. This NodeList includes all child nodes, including both element nodes and other node types such as text nodes and comment nodes. It enables you to traverse the DOM tree and perform various operations on the child elements of your target HTML elements.
Sample Code: Using childNodes
Let's say we have the following HTML document:
<!DOCTYPE html>
<html>
<head>
<title>childNodes Example</title>
</head>
<body>
<div id="mainContainer">
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
</div>
</body>
</html>
To use childNodes
to access child elements, you'll need to include a JavaScript <script>
tag in your HTML document. For this example, we will add an inline script, although it's generally recommended to use external JavaScript files for larger projects.
Here's how you can access all child elements of the div
element with the ID mainContainer
and change their font family:
<!DOCTYPE html>
<html>
<head>
<title>childNodes Example</title>
</head>
<body>
<div id="mainContainer">
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
</div>
<script>
// Select the element with the ID "mainContainer"
var mainContainer = document.getElementById('mainContainer');
// Access its child nodes
var childNodes = mainContainer.childNodes;
// Loop through the NodeList and change the font family of each element node
for (var i = 0; i < childNodes.length; i++) {
if (childNodes[i].nodeType === 1) {
// Check if the node is an element node
childNodes[i].style.fontFamily = 'Arial, sans-serif';
}
}
</script>
</body>
</html>
After running this code, the font family of the h1
and p
elements inside the div
element with the ID mainContainer
will be changed to "Arial, sans-serif".
Conclusion
The childNodes
property is a useful tool for accessing and manipulating child elements of a given HTML element in the DOM. By mastering this property, you can easily traverse the DOM tree and perform various operations on child elements, allowing you to create dynamic and interactive web pages.