Check the elements has class by Javascript

To check the element has a class by Javascript, you just use contains method of classList property like this example:

 
Contents...


In Javascript:

	const element = document.querySelector("#element");
	const hasClass = element.classList.contains("element-class");
    console.log(hasClass) // True


Explain: We use querySelector to get element by Id (#element), then check the element has class by classList.contains method (element-class)

If you want to check multiple elements by class name, your code will be:

HTML:

 
Contents...
Contents...
Contents...


Javascript:

  const elements = document.querySelectorAll(".element-class");
  let hasClass = false;
  for(let element of elements) {
    const checkHasClass = element.classList.contains("active-class");
    if(checkHasClass){
      hasClass = checkHasClass;
    }
  }
  console.log(hasClass) // True


© 2019 4codev

Created with love by Sil.