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?