admin管理员组文章数量:1221308
I want to check if any element in a NodeList has a specific class.
For example, with jQuery I just do something like:
//if any .item element has active class, return true
var isActive = $(".item").hasClass("active");
Only with Javascript I could do, but with a slightly longer code:
var isActive = false;
var items = Array.from(document.getElementsByClassName("item"));
items.forEach(function(item, index) {
if(item.className.indexOf('active') > 0) {
isActive = true;
}
});
alert(isActive);
<div class="item">1</div>
<div class="item">2</div>
<div class="item active">3</div>
<div class="item">4</div>
I want to check if any element in a NodeList has a specific class.
For example, with jQuery I just do something like:
//if any .item element has active class, return true
var isActive = $(".item").hasClass("active");
Only with Javascript I could do, but with a slightly longer code:
var isActive = false;
var items = Array.from(document.getElementsByClassName("item"));
items.forEach(function(item, index) {
if(item.className.indexOf('active') > 0) {
isActive = true;
}
});
alert(isActive);
<div class="item">1</div>
<div class="item">2</div>
<div class="item active">3</div>
<div class="item">4</div>
How can I do this with ES6? There is a helper for selectors?
Thanks!
Share Improve this question asked Aug 23, 2016 at 14:18 Adriano GodoyAdriano Godoy 1,5683 gold badges11 silver badges21 bronze badges 2- 2 "There is a helper for selectors?" No, there isn't. Selectors are a part of Web APIs, JS has no support for selectors. – Teemu Commented Aug 23, 2016 at 14:24
- 3 ES6 (ES2015 now) really doesn't have anything to do with DOM operations or CSS selectors; those are browser environment features. – Pointy Commented Aug 23, 2016 at 14:24
4 Answers
Reset to default 8Array.from(document.getElementsByClassName("item")).some(({classList}) =>
classList.contains('active'))
is probably the best ES6 can give you, which is essentially the same as your code above.
It has nothing to do with ES2015, but you can use document.querySelector()
much like the basic jQuery API:
var isActive = document.querySelector(".item.active") != null;
You don't really need ES6 to do the same thing in vanilla JS.
// jQuery
var isActive = $(".item").hasClass("active");
// Plain JavaScript
var isActive = document.querySelector('.item').classList.contains('active');
You can .find() on a nodelist and return the first true result.
const activeEl = Array.prototype.find.call (items, item => item.classList.contains('active'));
本文标签: javascriptCheck if any element in a NodeList has a specific class using ES6Stack Overflow
版权声明:本文标题:javascript - Check if any element in a NodeList has a specific class using ES6 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739262247a2155425.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论