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
}
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.
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:
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.
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 ...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With