Last updated: Mar 5, 2024
Reading timeยท2 min
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.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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.
We added a click
event listener to the child
element.
Every time the element is clicked, the handleClick
function is invoked.
We used the
target property
on the event
object to access the parent element.
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 which DOM element 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
.
You can learn more about the related topics by checking out the following tutorials: