I'm trying to figure out how to write an if statement that works something like this:
if (element contains class 1 && class 2) {
// do this
}
How do I write that if statement to check for multiple classes?
Is there a way to make the .contains method check for more than one class?
What I've found so far:
How to check class of multiple class elements in javascript, without jquery
Problem is, it seems to be returning an array of all the classes that the element contains, which is not what I want. I need the function to check if the element contains the classes that I am supplying it with.
One of the solutions looks to me like it's asking us to create our own function to do this, but is there a native method on JS which will do the trick?
I'm quite new to this stuff and I really appreciate the patience you guys have shown in answering my questions.
Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names.
HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.
We can use the classList property of the DOM element to check if the element contains a specific class. Note: The classList property contains the live collection of classes present in the DOM element.
Put the class names you want to test for into an array, then use Array.prototype.every()
to check if all members of your array exist in the element's classList
:
console.log(['a', 'b'].every(e=>div.classList.contains(e)))
console.log(['a', 'b', 'c'].every(e=>div.classList.contains(e)))
<div class="a b" id="div"></div>
Unfortunately Element.classList
is read-only, so you cannot add anything to its prototype. You can however do that on the Array.prototype
:
Array.prototype.contains = function(...args) {
return [...args].every(c=>this.includes(c))
}
console.log([...div.classList].contains('a', 'b'))
console.log([...div.classList].contains('a', 'c'))
console.log([...div.classList].contains('a', 'c.d'))
<div class="a b c.d" id="div"></div>
Important: Please note that this violates the basic OOP rule Do not modify objects you don't own. As such, it would be better to create a named function taking the element and an array with a list of classes to test for.
You can use the .matches()
API on the element, and it's pretty well-supported now:
if (element.matches(".class1.class2")) ...
It's like a built-in version of jQuery .is()
.
Documentation link.
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