60 lines
1.6 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
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.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
if ( $( "div.foo" ) ) { // Noncompliant
// this code always runs, even when the selector didn't match any elements
// ...
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
// Testing whether a selection contains elements.
if ( $( "div.foo" ).length > 0) {
// this code only runs if elements were found
// ...
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use the "length" property to see whether this selection contains elements.
'''
== Comments And Links
(visible only on this page)
=== on 26 Mar 2015, 17:11:46 Linda Martin wrote:
\[~ann.campbell.2] Assigned for review and completion. The description is a copy/paste of \https://learn.jquery.com/using-jquery-core/selecting-elements/, I was afraid that if I started to rephrase it would not make any sens anymore.
=== on 27 Mar 2015, 15:24:13 Ann Campbell wrote:
double-check me, please [~linda.martin]
=== on 19 May 2015, 15:54:00 Linda Martin wrote:
Reviewed.
=== on 24 Apr 2017, 10:24:45 Elena Vilchik wrote:
\[~ann.campbell.2] why minor?
=== on 1 Nov 2019, 17:29:53 Elena Vilchik wrote:
See \https://github.com/SonarSource/SonarJS/issues/1698
endif::env-github,rspecator-view[]