What's the correct way to check return value from `querySelectorAll`?
Asked Answered
D

2

6

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?

Dampen answered 17/9, 2015 at 18:53 Comment(0)
C
5

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.

Cairo answered 17/9, 2015 at 18:56 Comment(2)
@JamesThorpe Thanks, have updated my answer.. and knowledge!Cairo
No problems - be aware that it's specifically non-live, ie it's elements won't update. In some cases you have live ones as documented on that pageHomocyclic
C
3

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.

Clop answered 17/9, 2015 at 18:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.