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?
That'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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With