Using firstChild in JavaScript DOM (Live Playground)
In this tutorial, we will learn how to use the firstChild
property in JavaScript to access and manipulate the first child element of a given HTML element in the DOM. We'll cover the basics of the firstChild property and provide sample code with explanations.
What is firstChild?
The firstChild
property is a built-in JavaScript DOM property that allows you to access the first child node of a given HTML element in the DOM hierarchy. This property returns the first child node, or null
if the element has no child nodes. Note that the firstChild
property may return other types of nodes, such as text nodes or comment nodes, in addition to element nodes.
Sample Code: Using firstChild
Let's say we have the following HTML document:
<!DOCTYPE html>
<html>
<head>
<title>firstChild 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 firstChild
to access the first child element, 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 the first child element of the div
element with the ID mainContainer
and change its text color:
<!DOCTYPE html>
<html>
<head>
<title>firstChild 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 first child node
var firstChildNode = mainContainer.firstChild;
// If the first child node is an element node, change its text color
if (firstChildNode.nodeType === 1) {
firstChildNode.style.color = 'blue';
}
</script>
</body>
</html>
After running this code, the text color of the h1
element inside the div element with the ID mainContainer
will be changed to "blue".
Conclusion
The firstChild
property is a useful tool for accessing and manipulating the first child element 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.