Definition and Usage
The classList.contains() method checks whether the specified class attribute value exists in a DOM element. It returns true if the value exists and false otherwise.
You cannot check multiple class attribute values at once using classList.contains().
Note
Strictly speaking, it should not be described as checking whether a value exists in the class attribute, but rather as checking whether a class name exists in the list of class names, which is the value of the class attribute. The class attribute specifies one or more class names for an element, and its value is a list of class names separated by spaces. Although classList.contains() should technically be described as checking whether a class name exists in the list of class names that is the value of the element's class attribute, for consistency, this document uses the expression "check a class value".
Syntax
element.classList.contains(className)
The contains() function is a method of the classList object.
Parameters
className |
Required. The class value to check in the element (as a string). |
|---|
Return Value
Returns true if the specified class value exists in the element, and false otherwise.
Example
<video src="video.mp4" class="a b c"></video>
const myVideo = document.querySelector("video");
console.log(myVideo.classList.contains("a")); // true
console.log(myVideo.classList.contains("b")); // true
console.log(myVideo.classList.contains("d")); // false
Code Explanation
The querySelector() function returns the first element that matches the specified CSS selector within the HTML document or a specific element.
Because classList.contains() directly checks an element's class value to evaluate conditions, you can write concise and readable code.
Things to Keep in Mind
classList.add(), which adds class values to an element, and classList.remove(), which removes class values from an element, can add or remove multiple class values by separating them with commas (,) in their parameters.
Therefore, do not assume that classList.contains() can also check multiple class values by separating them with commas (,) in its parameter.
You cannot check multiple class values at once using classList.contains(). It accepts only one parameter, which must be a string.
Browser Compatibility
| Method |
Desktop Chrome
|
Desktop Edge
|
Desktop Firefox
|
Safari
|
|---|---|---|---|---|
classList.contains()
|
8 | 12 | 3.6 | 5.1 |
Specifications
| Specification | |
|---|---|
classList.contains()
|
DOM Standard #ref-for-dom-domtokenlist-contains① |
See Also
- JavaScript classList Object – Manipulating the Class Attribute of DOM Elements
- JavaScript classList.add() – Add Class Values to an Element
- JavaScript classList.remove() – Remove Class Values from an Element
- JavaScript classList.toggle() – Add a Class Value If It Does Not Exist, or Remove It If It Does
- JavaScript hasAttribute() Function – Checking If an Element Has an Attribute