1

I'm trying to use JS to check if an html tag contains a specific class

What I have so far (doesn't work)

if (html.classList.contains('test')) {

}
<html class="test">
  • Possible duplicate of [1]: https://stackoverflow.com/questions/5898656/check-if-an-element-contains-a-class-in-javascript – indefinite May 30 '19 at 03:00
  • What is `html` in this context? If it does point to this element, then that should work: https://plnkr.co/edit/rZvNJZ3JThP1LQaHtOb6?p=preview – Kaiido May 30 '19 at 03:22

1 Answers1

4

You can determine the class within the classList of the element.

let el = document.querySelector('html');
var classList = el.classList;
console.log(classList.contains('test')); // gives true
<html class="test">

You can also grab the className (which is a string of all applied classes and use .indexOf();

let el = document.querySelector('html');
var className = el.className;
console.log(className); // gives 'test test2'
console.log(className.indexOf('test') > -1); // gives true
<html class="test test2">

If you have access to jQuery, the .hasClass() method is what you want

let test = $('html').hasClass('test');
console.log(test); // gives true
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html class="test">
gavgrif
  • 15,194
  • 2
  • 25
  • 27
  • Your first snippet is what they are doing. Can you explain why it didn't work for them? – Kaiido May 30 '19 at 03:24
  • @Kaiido - hey good point - i didn't actually notice that :) - my guess is that they are not defining the html element (like I do with let el = document.querySelector('html');)and so there is no context for the classList. – gavgrif May 30 '19 at 03:28
  • Yes that's also my "guess", hence my close-vote as missing an [MCVE] since we can only "guess" what's wrong. (note that this element is accessible through `document.documentElement` property) – Kaiido May 30 '19 at 03:32