Add class to the clicked element in JavaScript
Question:
How to add class to the clicked element in JavaScript? Answer:
document.addEventListener('click', (evt) => {
evt.target.classList.add('clicked-style');
});
Description:
In order to add a CSS class to the element that the user clicked on, we first need to register an event listener. If you want to do this for all existing HTML elements you can do it with the following code:
document.addEventListener('click', (event) => {
/* ... */
});
The next step is to find out which tag the user clicked on. This can be read from the target
attribute of the event
object received as a parameter. Once you have the required element, you just need to add the desired CSS class to the classList
property using the add
method.
document.addEventListener('click', (event) => {
event.target.classList.add('clicked-style');
});
Reference:
addEventListener
The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
JavaScript:
addEventListener(type, listener);
TypeScript:
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
Examples:
element.addEventListener('click', (evt) => {
console.log('Clicked');
});
DOMTokenList.add
The add() method of the DOMTokenList interface adds the given tokens to the list, omitting any that are already present.
JavaScript:
add(token0);
TypeScript:
add(...tokens: string[]): void;
Examples:
myElement.classList.add("my-class-1", "my-class-2");
Share "How to add class to the clicked element in JavaScript?"
Related snippets:
- Create HTML element with attributes in JavaScript
- Get element by ID in React
- Set the required attribute in JavaScript
- Get elements by data attribute in JavaScript
- Add class to the clicked element in JavaScript
- Add class to multiple elements in JavaScript
- Add class to element if it does not already exists with JavaScript
- Add data attribute to element in JavaScript
- Add CSS class to body with JavaScript
- Add class to parent element in JavaScript
- Toggle fullscreen and normal mode with JavaScript
- Play video in fullscreen with vanilla JavaScript
- Select HTML elements by CSS selectors in vanilla JavaScript
- Exit from fullscreen mode on click in JavaScript
- Switch browser to fullscreen mode with JavaScript
- Get the value of text input field in JavaScript
- Get element with data- attribute using vanilla JavaScript
- Get the value of selected radio button in JavaScript
- Get selected option from select using JavaScript
- Check if element is hidden in JavaScript
Tags:
add, class, clicked, element, div, vanilla, javascript Technical term:
Add class to the clicked element in JavaScript