Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
To get the id of the parent element on click:
event.target
property to get the element the user clicked on.parentElement
property to get the parent and access its id
property.Here is the HTML for the examples in this article.
<!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.
const child = document.getElementById('child'); child.addEventListener('click', function handleClick(event) { // 👇️ "parent" console.log(event.target.parentElement.id); });
If you load the page and click on the child
element, you will see the string
parent
logged to the console.
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.
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.
const child = document.getElementById('child'); child.addEventListener('click', function handleClick(event) { console.log(event.target); // 👉️ p#child // 👇️ "parent" console.log(event.target.parentElement.id); });
The target
property on the event object is useful when you need a generic way
to access the element the event
was dispatched on.
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.
const child = document.getElementById('child'); child.addEventListener('click', function handleClick(event) { // 👇️ "parent" console.log(child.parentElement.id); });
This example logs the id of the direct parent of the element with id
set to
child
.