Home > other >  Check if element contains any of multiple classes in JavaScript
Check if element contains any of multiple classes in JavaScript

Time:03-15

I need to check to see if an element contains ANY one of multiple classes in plain JavaScript. Is there a way to do the following with less code / more concisely?

let element = document.querySelector('.element');
if( element.classList.contains('class-1') || element.classList.contains('class-2') || element.classList.contains('class-3') {
  // do something
}

Thanks in advance for your help.

CodePudding user response:

You can do if(element.matches(selector)) //returns true or false where selector would be selector = ".class-1, .class-2, .class-3" in your case. This works with any CSS Selector. If you want every class to be present, you would need selector = ".class-1.class-2.class-3 for example. You can learn more about CSS-Selectors here: https://www.w3schools.com/cssref/css_selectors.asp

  • Related