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 ofhtml
element. Bothbody
andhead
elements are child nodes of thehtml
element.
Are we missing something? Help us improve this article. Reach out to us.
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 ofhtml
element. Bothbody
andhead
elements are child nodes of thehtml
element.
Are you looking for other code tips?
JS Nooby
Javascript connoisseur