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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

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.

本文标签: javascriptWhat39s the correct way to check return value from querySelectorAllStack Overflow