Once you've made a selection, you typically want to know whether it actually found anything. Since selectors always return an object (the
set of selected DOM elements), the best way to see whether your selection found anything is to test the returned object's .length
property.
if ( $( "div.foo" ) ) { // Noncompliant
// this code always runs, even when the selector didn't match any elements
// ...
}
// Testing whether a selection contains elements.
if ( $( "div.foo" ).length > 0) {
// this code only runs if elements were found
// ...
}