cup_of
cup_of

Reputation: 6687

Check if multiple elements exist in one if statement in jQuery

I am using waypoints.js and it breaks when I am not on the page that it is targeting.

To fix this I have to check if the element exists on the page before running the waypoints function like this:

if (jQuery(".section-2-box").length) {
   //my code             
}

if (jQuery(".section-3-box").length) {
   //my code             
}

if (jQuery(".section-4-box").length) {
   //my code             
}

It works, but the problem is that I have so many elements I need to check. I don't want to have to write out 20 if statements.

Is it possible to just do one if statement to do some type of logic like "if all of these elements exist then run some code"?

Upvotes: 0

Views: 2317

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

If you know there is only one element with each of those classes, then a standard group selector can do it:

if (jQuery(".section-2-box, .section-3-box, .section-4-box").length === 3)

If not (there might be two section-2-boxs and no section-3-box), you probably have to throw jQuery-specific :firsts in there:

if (jQuery(".section-2-box:first, .section-3-box:first, .section-4-box:first").length === 3)

Example:

if (jQuery(".section-2-box:first, .section-3-box:first, .section-4-box:first").length === 3) {
  console.log("Yes");
} else {
  console.log("No");
}
<div>We should see "no" because there is no .section-3-box</div>
<div class="section-2-box"></div>
<div class="section-2-box"></div>
<div class="section-4-box"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 3

Related Questions