Check if multiple elements exist in one if statement in jQuery -
hello using waypoints.js , breaks when not on page targeting.
to fix have check if element exists on page before running waypoints function 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, problem have many elements need check. dont want have write out 20 if statements.
is possible 1 if statement type of logic if of these elements exist run code
?
if know there 1 element each of classes, standard group selector can it:
if (jquery(".section-2-box, .section-3-box, .section-4-box").length === 3)
if not (there might 2 section-2-box
s , no section-3-box
), have throw jquery-specific :first
s 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 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>
Comments
Post a Comment