Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 364
bodacydo Avatar asked Sep 17 '15 18:09

bodacydo


2 Answers

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.

like image 77
Curtis Avatar answered Sep 17 '22 17:09

Curtis


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.

like image 41
Josh Beam Avatar answered Sep 19 '22 17:09

Josh Beam