admin管理员组文章数量:1291236
When using querySelectorAll
, what is the correct way to check if it returned any elements?
It returns something that can't be checked for false
. This doesn't seem to work:
var elements = document.querySelectorAll('.class');
if (elements) {
// doesn't work, `elements` is always true
}
Right now I'm doing the following check via .length
property:
var elements = document.querySelectorAll('.class');
if (elements.length) {
// querySelectorAll returned DOM elements
}
Is this how you do it?
When using querySelectorAll
, what is the correct way to check if it returned any elements?
It returns something that can't be checked for false
. This doesn't seem to work:
var elements = document.querySelectorAll('.class');
if (elements) {
// doesn't work, `elements` is always true
}
Right now I'm doing the following check via .length
property:
var elements = document.querySelectorAll('.class');
if (elements.length) {
// querySelectorAll returned DOM elements
}
Is this how you do it?
Share Improve this question asked Sep 17, 2015 at 18:53 bodacydobodacydo 79.5k95 gold badges233 silver badges328 bronze badges2 Answers
Reset to default 6That's correct.
document.querySelectorAll('.class')
returns a non-live Node List, this will always be truthy.
Therefore you need to count the items in the list by using length
to determine if there are more than 0 items.
Yes. querySelectorAll
will return an array-like object, which has a length property (the actual object is a NodeList).
So,
if(elements.length > 0) {
// you have elements
}
// and
if(element.length === 0) {
// you don't have elements
}
The problem with doing if(elements)
is that []
is truthy, meaning it will always return true:
!![] === true
.
本文标签: javascriptWhat39s the correct way to check return value from querySelectorAllStack Overflow
版权声明:本文标题:javascript - What's the correct way to check return value from `querySelectorAll`? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741531001a2383753.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论