How to get the parent of an element in JavaScript

published: 25 Sep 2022

2 min read

How to get the parent of an element in JavaScript

To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object.

Let us say you have the following HTML code:

<div>
    <button id='btn'>Click Me</button>
</div>

The following example demonstrates how you can get the parent node of button:

const button = document.querySelector('#btn');

const div = button.parentNode;

console.log(div.classList[0]); // wrapper

The parentNode property is read-only, which means you can not modify it.

In HTML, the document is itself the parent node of html element. Both body and head elements are child nodes of the html element.

How to get the parent of an element in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming