Get ID of parent element on Click using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Get ID of parent element on Click using JavaScript #

To get the id of the parent element on click:

  1. Add a click event listener to the element.
  2. Use the event.target property to get the element the user clicked on.
  3. Use the parentElement property to get the parent and access its id property.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="parent"> <p id="child" style="background-color: salmon; width: 100px; height: 100px" > Child 1 </p> </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const child = document.getElementById('child'); child.addEventListener('click', function handleClick(event) { // 👇️ "parent" console.log(event.target.parentElement.id); });

get id of parent element on click

If you load the page and click on the child element, you will see the string parent logged to the console.

We added a click event listener to the child element. Every time it is clicked, the handleClick function is invoked.

We used the target property on the event object. The target property is a reference to the object (element) on which the event was dispatched.

In other words event.target gives us access to the DOM element the user clicked.

You can console.log the target property to see the DOM element which was clicked by the user.

index.js
const child = document.getElementById('child'); child.addEventListener('click', function handleClick(event) { console.log(event.target); // 👉️ p#child // 👇️ "parent" console.log(event.target.parentElement.id); });

get access to clicked element

The target property on the event object is useful when you need a generic way to access the element the event was dispatched on.

For example, if you add a click event listener on the document object, there is no good way to tell on which element the user clicked, other than event.target.

If you want to get the id of the parent element of a specific child, you can also access parentElement.id directly on the child element.

index.js
const child = document.getElementById('child'); child.addEventListener('click', function handleClick(event) { // 👇️ "parent" console.log(child.parentElement.id); });

get id of direct parent element on click

This example logs the id of the direct parent of the element with id set to child.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.