31 lines
797 B
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
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.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
if ( $( "div.foo" ) ) { // Noncompliant
// this code always runs, even when the selector didn't match any elements
// ...
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
// Testing whether a selection contains elements.
if ( $( "div.foo" ).length > 0) {
// this code only runs if elements were found
// ...
}
----
ifdef::env-github,rspecator-view[]
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]