Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if element contains any of multiple classes in JavaScript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading