Suppose you want to retrieve the value of the id attribute of a DOM element in your HTML document, such as an <a>
, a <button>
, or a <div>
, when the user clicks on it.
What is the best way to accomplish this?
To get the id
attribute of a DOM element on click, create an event listener using AddEventListener()
and retrieve the id of the clicked object using Element.target()
.
This tutorial will show you exactly how to do this in two steps: creating an event listener for clicks, then applying the method to get the id attribute of clicked elements.
Creating an Event Listener
In JavaScript, a click (or, on touch screen devices, a tap) is an event that you can listen and react to.
You do this by creating an event listener that, as the name implies, listens to the user’s interactions with the DOM elements on the frontend and fires when the event being listened to takes place.
You do this with the EventTarget.AddEventListener()
method.
The EventTarget.AddEventListener()
method specifies a string that gets returned or a function that gets called whenever the event that’s being listened to occurs.
Its syntax is as follows:
// Event listener method syntax
EventTarget.addEventListener(type, listener);
With this method, you can target all clicks, regardless of the element:
// Target all clicks on any element
document.addEventListener('click',() =>
{
console.log("An element was clicked.")
}
);
Or, by using the querySelectorAll()
method and a loop to iterate over its results, you can use CSS selectors to target one or more occurences of a specific type of DOM elements, such as links or links with a given attribute:
// Create event listener for all link clicks
document.querySelectorAll('a').forEach(occurence => {
occurence.addEventListener('click', (e) => {
console.log('A link was clicked');
});
});
// Create event listener for link clicks with a custom attribute
document.querySelectorAll('a[data-type="link-outbound"]').forEach(occurence => {
occurence.addEventListener('click', (e) => {
console.log('An outbound link was clicked');
});
});
Although there are other ways to target DOM elements in JavaScript, the querySelectorAll()
method provides all the utility you need for the majority of use cases by allowing you to use CSS selectors.
Related: Event Listeners for Multiple Elements in JavaScript
Retrieving the id Attribute
Now that you know how to create event listeners for clicks on elements, the next step is for you to learn how to retrieve the id
attribute of the elements that the user clicked.
We can do this by passing on the e
parameter to the function, which stands for “event,” that gets called on click.
We can then use the Event.target()
Web API to retrieve the id attribute of the DOM object to which the event was attached:
// Create event listener
document.addEventListener('click', (e) =>
{
// Retrieve id from clicked element
let elementId = e.target.id;
// If element has id
if (elementId !== '') {
console.log(elementId);
}
// If element has no id
else {
console.log("An element without an id was clicked.");
}
}
);
If you opened up your browser’s developer tools, ran this code in the console, and clicked around on this website right now, this is what you’d see:
In Conclusion
I hope this tutorial helped. I recently found myself tackling this challenge as I was implementing a data layer for analytics purposes on one of my websites. It took me a few iterations (and a few hours) to get to the best solution, and I believe this is it.
If you have any questions, or you want to share other ways to achieve this with the rest of this post’s readers, be sure to leave a reply below.
I love it! And I kind of understand its your “analytics purposes” drove you to this “best solution” — I came from analytics background, I know how the mind of analytics people works, and what they appreciate! I appreciate this solution, including the way you articulate it! In my view, this solution is comprehensive by concept, and anyone can cut out a small piece from it for any particular convenience that appeals to him at time being.
Glad you liked it, Yadong! And thank you for stopping by, your comment made my day!
Best,
Jim
You made this super easy to understand. Well written, Great job, Thank You!!!
Very clear written and easy understandable! Really good job, Thank you.