Skip to main content

Using previousSibling in JavaScript DOM (Live Playground)

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

What is previousSibling?

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

Sample Code: Using previousSibling

Let's say we have the following HTML document:

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

To use previousSibling to access the previous 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 previous sibling element of the p element with the ID mainParagraph and change its text color:

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

<script>
// Select the element with the ID "mainParagraph"
var mainParagraph = document.getElementById('mainParagraph');

// Access its previous sibling node
var previousSiblingNode = mainParagraph.previousSibling;

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

Live Playground, Try it Yourself

Conclusion

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