Skip to content

How to get parent node name of a HTML element?

To get the parent node name and other properties of an HTML element, we can use the .parentNode attribute. Every html element has parentNode attribute that holds the data of the parent node.

Let’s take a sample HTML.

<html>

<head>
	<title>A Simple HTML Document</title>
</head>

<body>
	<div id="firstDiv">
		<div id="secondDiv">
			<p>A simple HTML document</p>
			<p>It only has two paragraphs</p>
		</div>
	</div>
</body>

</html>

To get the parent node of the div secondDiv we can use the following piece of code.

document.getElementById('secondDiv').parentNode;

This would return the following.

<div id="firstDiv">
		<div id="secondDiv">
			<p>A simple HTML document</p>
			<p>It only has two paragraphs</p>
		</div>
	</div>

To get the node name of the parent node..

document.getElementById('secondDiv').parentNode.nodeName;
// "DIV"

To get only the id of the parent node..

document.getElementById('secondDiv').parentNode.id;
"firstDiv"

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.