JQuery - selecting only every second element with .each?

Is it only possible to select every second element using the .each () function? If not, what are the alternatives?

+4
source share
4 answers

You can use : odd selector:

$("yourSelector:odd").each(function() { // Will be called on every second element. }); 
+9
source

This can help:

 $('li').each(function(index) { if(index%2) alert(index + ': ' + $(this).text()); }); 
+5
source

You can use: nth-child () selector.

 $("selector:nth-child(2)") 
+2
source

If you want to get a specific element / node or tag in a loop, for example,

 <p class="weekday" data-today="monday">Monday</p> <p class="weekday" data-today="tuesday">Tuesday</p> <p class="weekday" data-today="wednesday">Wednesday</p> <p class="weekday" data-today="thursday">Thursday</p> 

So, from above the code loop is executed, and we want a certain field to be selected for this, we should use the jQuery selection, which can only select the waiting element from the loop above, so the code will be

 $('.weekdays:eq(n)'); 

eg.

 $('.weekdays:eq(0)'); 

as well as in another way

 $('.weekday').find('p').first('.weekdays').next()/last()/prev(); 

but the first method is more efficient when the HTML <tag> has a unique class name.

NOTE. The second method is used when they are not a class name in the target element or node.

for a more consistent https://api.jquery.com/eq/

0
source

All Articles