DOMTokenList contains()
Method: Checking Token Existence
The contains()
method of the DOMTokenList
interface is used to check if a specified token exists within the list of tokens associated with an HTML element’s attribute, such as the class
attribute. This method returns a boolean value: true
if the token is present, and false
otherwise. It’s a simple yet powerful way to verify the presence of a class or other token without iterating through the entire list.
Syntax
domTokenList.contains(token);
Parameters
token
: A string representing the token you want to check for in theDOMTokenList
.
Return Value
- A
boolean
value: true
: If theDOMTokenList
contains the specifiedtoken
.false
: If theDOMTokenList
does not contain the specifiedtoken
.
Usage Notes
- The
contains()
method performs a case-sensitive comparison. - It is commonly used with the
classList
property of HTML elements to check for the presence of a specific class. - The method is straightforward and efficient for simple token existence checks.
Examples
Basic Example: Checking Class Existence
This example demonstrates how to use contains()
to check if an element has a specific class.
<div id="myElement" class="box highlighted"></div>
<script>
const element_1 = document.getElementById("myElement");
const classList_1 = element_1.classList;
console.log(classList_1.contains("box")); // Output: true
console.log(classList_1.contains("highlighted")); // Output: true
console.log(classList_1.contains("hidden")); // Output: false
</script>
In this example, we retrieve the classList
of an element and then use contains()
to check for the presence of the “box”, “highlighted”, and “hidden” classes.
Checking Multiple Tokens
You can use contains()
multiple times to check for multiple tokens.
<div id="myElement2" class="button primary large"></div>
<script>
const element_2 = document.getElementById("myElement2");
const classList_2 = element_2.classList;
const hasPrimary = classList_2.contains("primary");
const hasLarge = classList_2.contains("large");
if (hasPrimary && hasLarge) {
console.log("Element has both 'primary' and 'large' classes.");
} else {
console.log("Element does not have both classes.");
}
</script>
This example checks if an element has both the “primary” and “large” classes and logs a message accordingly.
Dynamic Class Checking
The contains()
method is often used in dynamic scenarios where you need to check for a class before performing an action.
<button id="myButton">Click Me</button>
<script>
const button_1 = document.getElementById("myButton");
button_1.addEventListener("click", function () {
if (!this.classList.contains("disabled")) {
console.log("Button was clicked!");
this.classList.add("clicked");
} else {
console.log("Button is disabled and cannot be clicked.");
}
});
// Simulate disabling the button after some time
setTimeout(() => {
button_1.classList.add("disabled");
}, 3000);
</script>
In this example, we add a click event listener to a button. The listener checks if the button has the “disabled” class before logging a message and adding the “clicked” class. This prevents the button’s action from being triggered if it is disabled.
Using contains()
with Other Token Lists
While commonly used with classList
, contains()
can also be used with other DOMTokenList
instances, such as the relList
of <a>
elements.
<a id="myLink" href="#" rel="nofollow noreferrer">My Link</a>
<script>
const link_1 = document.getElementById("myLink");
const relList_1 = link_1.relList;
console.log(relList_1.contains("nofollow")); // Output: true
console.log(relList_1.contains("noreferrer")); // Output: true
console.log(relList_1.contains("noopener")); // Output: false
</script>
This example demonstrates checking for rel
attribute values using relList
.
Practical Use Cases
- Conditional Styling: Apply different styles based on the presence of specific classes.
- Feature Toggling: Enable or disable features based on the existence of a class.
- Form Validation: Validate form fields based on the presence of specific classes.
- Accessibility: Implement accessibility features based on the presence of ARIA attributes.
Tips and Best Practices
- Case Sensitivity: Be mindful of case sensitivity when using
contains()
."active"
is different from"Active"
. - Performance: For simple checks,
contains()
is generally efficient. However, for complex scenarios, consider alternative approaches. - Readability: Use descriptive variable names to improve code readability.
Browser Support
The DOMTokenList.contains()
method is widely supported across modern browsers.
Conclusion
The DOMTokenList contains()
method is a useful and efficient way to check for the existence of tokens in an HTML element’s attribute. It simplifies conditional logic and enhances the interactivity of web applications. By understanding its syntax and use cases, you can leverage this method to create more dynamic and responsive user experiences.