Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly does element.classList.contains() work in JavaScript?

Tags:

javascript

I needed to use element.classList.contains('some-class') to check if an element contains at least one of three classes, so I wrote:

if (element.classList.contains('class1', 'class2', 'class3')) {
  // do stuff here
}

The result was - if the element has 'class1', it returns true, no matter if it has 'class2' or/and 'class3', and // do stuff here executes. However, if it has 'class2' and/or 'class3', it returns false and // do stuff here does not execute.

I worked around it with:

if (element.classList.contains('class1') || element.classList.contains('class2') || element.classList.contains('class3')) {
  // do stuff here 
}
like image 975
Ralitsa Velikova Avatar asked Dec 19 '14 12:12

Ralitsa Velikova


People also ask

What is the use of classlist in JavaScript?

The Element.classList is a read-only property that returns a live DOMTokenList collection of the class attributes of the element. This can then be used to manipulate the class list. Using classList is a convenient alternative to accessing an element's list of classes as a space-delimited string via element.className.

How to check if an element contains a class in JavaScript?

To check if an element contains a class, you use the contains () method of the classList property of the element: * *Suppose you have the following element: To check if the element contains the secondary class, you use the following code: The following returns false because the element doesn’t have the class error:

How to add classes to the class List of an element?

Then, iterate over the elements of the classList and show the classes in the Console window. To add one or more CSS classes to the class list of an element, you use the add () method of the classList.

How to add and remove classes in JavaScript classlist?

The JavaScript classList property consists of following methods through which we can perform different operations on the class elements: add (): The add () method is used for adding one or more classes to the element. remove (): The remove () method is used for removing one or more classes from the ...


2 Answers

This function only takes one parameter. The contains method is used to check if your classList contains a singular element. The code block that you have posted at the bottom is a good workaround. But unfortunately what you are trying to do at the top is beyond the reach of the classList API.

like image 139
Martin McKeaveney Avatar answered Nov 15 '22 21:11

Martin McKeaveney


It tells you if the class name you pass as the first argument is one of the classes the element is a member of.

As with all JavaScript functions, you can pass as many additional arguments are you like. The contains function just doesn't do anything with them.

like image 31
Quentin Avatar answered Nov 15 '22 21:11

Quentin