\n\n\nIn this scenario, clicking the button calls the highlight function, passing in this (the button element), which is then used to add the 'active' class to the button.","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Nikita Barsukov","url":"https://explain.codes//author/nikita-barsukov"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2025-02-19T20:00:01.238Z","dateModified":"2025-02-19T20:00:03.030Z"}
Explain Codes LogoExplain Codes Logo

How to pass an element to a JavaScript onclick function and assign a class to that clicked element

javascript
event-handling
vanilla-javascript
best-practices
Nikita BarsukovbyNikita Barsukov·Feb 19, 2025
TLDR

You can use this inside the onclick event to target the clicked HTML element, then apply element.classList.add('class-name') to assign a new class:

<button onclick="highlight(this);">Click me</button> <script> function highlight(element) { element.classList.add('active'); } </script>

In this scenario, clicking the button calls the highlight function, passing in this (the button element), which is then used to add the 'active' class to the button.

Interacting with multiple elements

When you're dealing with multiple clickable items like tabs or menu items, you'd typically only want the item you clicked on to be active. Let's take a look at how to achieve that:

<ul> <li onclick="makeActive(this)">Tab 1</li> <li onclick="makeActive(this)">Tab 2</li> <li onclick="makeActive(this)">Tab 3</li> </ul> <script> function makeActive(tab) { // Hey! Who turned off the lights on all tabs?! document.querySelectorAll('.active').forEach(tab => tab.classList.remove('active')); // One tab to rule them all tab.classList.add('active'); } </script>

The script first turns off active status of every other tab, then fires up the clicked tab. Lightbulb moment, huh?!

Seriously leveled up event handling

From inline to external with addEventListener

To improve code organization and maintainability, we can use addEventListener:

document.querySelectorAll('.tab').forEach(tab => { tab.addEventListener('click', (event) => { // Guess we're having a lights-out party document.querySelectorAll('.active').forEach(tab => tab.classList.remove('active')); // And then there was light, on this one tab event.target.classList.add('active'); }); });

Making use of data-* attributes

Adding data-* attributes helps mapping element to its representation and handling:

<button data-tab="1" onclick="activateTab(this)">Tab 1</button> <button data-tab="2" onclick="activateTab(this)">Tab 2</button> <script> function activateTab(element) { // One by one, the lights go out document.querySelectorAll('[data-tab]').forEach(tab => tab.classList.remove('active')); // Abracadabra! Let there be light element.classList.add('active'); } </script>

Streamlining events with Event Delegation

Event delegation is ideal when dealing with a large number of elements or dynamically added elements:

document.addEventListener('click', (event) => { // Are you the chosen one? (Tab, I mean) if (event.target.matches('.tab')) { setActiveTab(event.target); } }); function setActiveTab(tab) { // Add active class to the anointed tab // Cue the heavenly choir tab.classList.add('active'); }

The dark corners — pitfalls and best practices

Keeps your 'this' in check

When using this in an inline event handler, it's key to understand that it refers to the HTML element receiving the event.

Mind your syntax

Keep an eye out for typos or syntax errors that might hinder code execution. It's like checking the stage for banana peels before starting the concert.

Ditch the jQuery

In a world where every millisecond counts, go for vanilla JavaScript over jQuery. It’s like choosing acoustic over electric in an intimate jazz bar.

The right target audience

Make sure you're adding classes to the right element level for the visual output you're aiming for. Akin to choosing whether to mic the lead singer or the choir.