简体   繁体   中英

IE9 Javascript classList Property

IE9不支持classList属性,反正这行JavaScript使其可以在IE9中工作

this.wrap.classList.add("myClass") 

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.)

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> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM