Skip to main content

Using lastChild in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to use the lastChild property in JavaScript to access and manipulate the last child element of a given HTML element in the DOM. We'll cover the basics of the lastChild property and provide sample code with explanations.

What is lastChild?

The lastChild property is a built-in JavaScript DOM property that allows you to access the last child node of a given HTML element in the DOM hierarchy. This property returns the last child node, or null if the element has no child nodes. Note that the lastChild property may return other types of nodes, such as text nodes or comment nodes, in addition to element nodes.

Sample Code: Using lastChild

Let's say we have the following HTML document:

<!DOCTYPE html>
<html>
<head>
<title>lastChild 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 lastChild to access the last 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 last child element of the div element with the ID mainContainer and change its text color:

<!DOCTYPE html>
<html>
<head>
<title>lastChild 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 last child node
var lastChildNode = mainContainer.lastChild;

// If the last child node is an element node, change its text color
if (lastChildNode.nodeType === 1) {
lastChildNode.style.color = 'red';
}
</script>
</body>
</html>

After running this code, the text color of the p element inside the div element with the ID mainContainer will be changed to "red".

Live Playground, Try it Yourself

Conclusion

The lastChild property is a useful tool for accessing and manipulating the last 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.