Languages
[Edit]
EN

JavaScript - add, remove, get and check element class name

2 points
Created by:
Savannah
559

In this article, we want to show a simple summary of the operations on the classList property located inside the element. The class list lets to add single class names into elements under JavaScript.

Note:

The element can have only unique class names like Set does.

 

 OperationDescription
1add

With classList.add() we are able to add a single class name to element classes.

2get

By default classList.get() function is not available.

Go to below classList.contains() function description to find an alternative.

3set

When classList.toggle() is used with two parameters work like set() method:

  • adding class name when the second parameter is true,
    e.g. classList.toggle('class-name', true)
  • removing class name when the second parameter is false,
    e.g. classList.toggle('class-name', false)
4remove

With classList.remove() we are able to remove a single class name from element classes.

5replace

With classList.replace() we are able to replace a single class name from element classes with a new one.

6toggle

When classList.toggle() is used with a single parameter:

  • removes class name if already exists in the element,
  • adds class name in another case.

In other words, we can say: the classList.toggle() method works like a switch.

When classList.toggle() added class name it returns true, in other cases false (when removed class name).

Note:

Go to the 3. set example to see the toggle() with two arguments. 

7contains

With classList.contains() we are able to check if the element's classList contains the given class name.

8clear

With classList.contains() we are able to check if the element's classList contains the given class name.

9iterating

In the example below, we use forEach() method to iterate and display class names from the element's classList.

Alternative titles

  1. JavaScript - element classList usage example
  2. JavaScript - element class list usage example
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join