Reputation: 13
IE9 doesn't support the classList property is there anyway around this line of javascript for it to work in IE9
this.wrap.classList.add("myClass")
Upvotes: 0
Views: 269
Reputation: 1252
Building on the previous answers, if you don't want to have to deal with the nitty gritty of regexes yourself, you could import jQuery and use jQuery's .hasClass()
method instead.
return $(document.body).hasClass("myClass");
jQuery handles dealing with cross-browser support.
Upvotes: -1
Reputation: 6664
An alternative:
const hasClass = ($element, className) => {
const match = new RegExp(`(^|\\s)${className}(\\s|$)`).test($element.className);
return $element.className && match;
};
const $el = document.querySelector('.foo');
alert(hasClass($el, 'foo'));
.foo {
background: tomato;
}
<div class="foo">Foobar</div>
Upvotes: 0
Reputation: 1075069
There are polyfills, but if you don't want to use one: Since className
is a space-separated list of the classes, you could use a regular expression:
return /(?:^|\s)myClass(?:$|\s)/.test(document.body.className);
(Sadly, we can't just use \b
[word boundary] since -
qualifies as a word boundary, but isn't a separator in the class list.)
Upvotes: 2