Skip to main content

Using parentNode in JavaScript DOM (Live Playground)

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

What is parentNode?

The parentNode property is a built-in JavaScript DOM property that allows you to access the parent element of a given HTML element in the DOM hierarchy. This property is read-only and returns the parent element, or null if the element has no parent. It enables you to traverse the DOM tree and perform various operations on the parent elements of your target HTML elements.

Sample Code: Using parentNode

Let's say we have the following HTML document:

<!DOCTYPE html>
<html>
<head>
<title>parentNode 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 parentNode to access parent 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 the parent element of the p element with the class mainParagraph and change its background color:

<!DOCTYPE html>
<html>
<head>
<title>parentNode 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 class "mainParagraph"
var mainParagraph = document.querySelector('.mainParagraph');

// Access its parent element
var parentElement = mainParagraph.parentNode;

// Change the background color of the parent element
parentElement.style.backgroundColor = '#f0f0f0';
</script>
</body>
</html>

After running this code, the background color of the div element with the ID mainContainer will be changed to "#f0f0f0".

Live Playground, Try it Yourself

Conclusion

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