How to Get the Class of a Clicked Element in JavaScript

Learn how to get the class of any, or specific, DOM element that the user clicks by creating an event listener.

Published Categorized as JavaScript, Web Dev

Suppose you want to retrieve the value of the class attribute of a DOM element in your HTML document, be it an <a>, a <button>, or a <div>, when users click it.

What is the best way to accomplish this?

To get the class 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.

First, we’ll create an event listener for clicks on your target element. Second, we’ll retrieve the class attribute of clicked elements using the method above.

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 Class Attribute

So far, so good. You learned how to create event listeners for clicks on DOM elements. Next, you need to learn how to retrieve the value of the class attribute of the DOM elements the user clicked.

You can do this by passing on the e parameter to the function,short for “event,” that gets called on click.

You can then use the Event.target() Web API to retrieve the className attribute of the DOM object to which the event in your event listener was attached:

// Target all clicks on any element
document.addEventListener('click',(e) =>
  {
    // Get element class(es)
    let elementClass = e.target.className;
    // If element has class(es)
    if (elementClass !== '') {
      console.log(elementClass);
    }
    // If element has no classes
    else {
      console.log('An element without a class 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:

Logging classes of clicked DOM elements in the console

If the clicked element has multiple classes, the function will return all classes, with pairs of adjacent classes separated by blank space.

For example:

Multiple classes for a clicked DOM element logged

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.

Leave a comment

Your email address will not be published.