Add class to multiple elements in JavaScript
Question:
How to add class to multiple elements in JavaScript? Answer:
const elementList = document.querySelectorAll('li');
elementList.forEach(el => el.classList.add('new-class'));
Description:
To add a CSS class to multiple HTML elements then you need to collect all of them first. You can do this using the querySelectorAll
method with the appropriate search query. For example to find all list items you can use the following code:
const listItems = document.querySelectorAll('li');
The next step is to iterate through the list. This can easily be done with forEach
.
listItems.forEach( ... );
After that, you only need to expand the classList
property of the current element in each iteration. The new CSS class can be added to the list using the add
method.
listItems.forEach(item => item.classList.add('new-class'));
Reference:
forEach
Executes a provided function once for each array element.
JavaScript:
forEach((element) => { /* … */ })
TypeScript:
forEach(callbackfn: (value: Node, key: number, parent: NodeList) => void, thisArg?: any): void;
Examples:
const items = [1, 2, 3];
items.forEach((item) => {
console.log(item * 2);
});
querySelectorAll
Returns a static NodeList representing a list of the document's elements that match the specified group of selectors.
JavaScript:
querySelectorAll(selectors)
TypeScript:
querySelectorAll(selectors: K): NodeListOf;
Examples:
const items = document.querySelectorAll(".highlighted > p");
Share "How to add class to multiple elements 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, append, css, class, multiple, elements, divs, vanilla, javascript Technical term:
Add class to multiple elements in JavaScript