Get ID of parent element in JavaScript DOM

Often it may be required to get the ID of the parent element of a child element in an HTML document to perform task. So here, I am going to show you the easiest way to get the ID of the parent element of a child element with JavaScript DOM.

For example, suppose we have an HTML that is given below:

<div id="ParentID">
  <div id="childID">Get the Parent ID</div>
</div>

You can see that we have a parent element with ID “parentID” and inside it, there is a child element having the ID “childID”. Now we have to get the parent ID of the child element with the ID “childID”.

We can do it very easily using just one line of JS code. Below is our JavaScript code to get the parent ID of our element:

alert (document.getElementById("childID").parentElement.id);

Using the above code, we are showing the ID of the parent element as an alert text.

In our code, we have used the parentElement property of JavaScript DOM. The parentElement property returns the parent element of the specified element.

Now if you run the code, you can see the ID of the parent element, in our case, we can see “ParentID” in the alert text.

Also, read: Start HTML5 video from a particular time in JavaScript

Leave a Reply

Your email address will not be published.