Skip to main content

Using nextSibling in JavaScript DOM (Live Playground)

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

What is nextSibling?

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

Sample Code: Using nextSibling

Let's say we have the following HTML document:

<!DOCTYPE html>
<html>
<head>
<title>nextSibling Example</title>
</head>
<body>
<div id="mainContainer">
<h1 id="mainHeading" class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
</div>
</body>
</html>

To use nextSibling to access the next sibling 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 next sibling element of the h1 element with the ID mainHeading and change its text color:

<!DOCTYPE html>
<html>
<head>
<title>nextSibling Example</title>
</head>
<body>
<div id="mainContainer">
<h1 id="mainHeading" 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 "mainHeading"
var mainHeading = document.getElementById('mainHeading');

// Access its next sibling node
var nextSiblingNode = mainHeading.nextSibling;

// If the next sibling node is an element node, change its text color
if (nextSiblingNode.nodeType === 1) {
nextSiblingNode.style.color = 'green';
}
</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 "green".

Live Playground, Try it Yourself

Conclusion

The nextSibling property is a useful tool for accessing and manipulating the next sibling 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 sibling elements, allowing you to create dynamic and interactive web pages.