AnApprentice
AnApprentice

Reputation: 110960

JQUERY each(), determining the # of matches so you can only act on the last one

When using JQUERY.each(), what is the way to obtain the value of matched items. I'd like to wrap an IF inside the each() to only act on the last match. thx

Upvotes: 2

Views: 509

Answers (5)

rob waminal
rob waminal

Reputation: 18419

instead of using each you can use :last if you only want to get the last item of your DOM elements for example

 <ul class="myUls">
     <li>one</li>
     <li>two</li>
     <li>three</li>
</ul>

in you script, you can say

var last = $('.myUls li:last');

the DOM of the last would be the <li>three</li>

moreover if you want to select an index of an array of DOM element you can use :eq() say for example above you want to select the DOM <li>two</li> you can do.

var two = $('.myUls li:eq(1)');

that will get you the two as <li>two</li>

Upvotes: 1

jasongetsdown
jasongetsdown

Reputation: 1305

The :last selector. In general though, if you want to know the position of the element you're iterating over with .each() it gets passed to the callback.

$('.selector').each(function(index, elem) {
    //index gets the position of the current elem
});

Upvotes: 0

EndangeredMassa
EndangeredMassa

Reputation: 17528

The .each() method tells you which index item you are currently working with.

$.each(myItems, function(index, value) { 
    if(index == myItems.length-1)
        doStuff(value);
});

It might be easier to just index the last item like so:

doStuff(myItems[myItems.length-1]);

Upvotes: 4

Jamie Wong
Jamie Wong

Reputation: 18350

As BrunoLM mentions, you should probably just use the :last selector.

If you do want to know the number of matches for whatever other reason, you can use .size(), or .length

e.g.

$("b").each(function(i) {
  if (i == $("b").size() - 1) {
    // do stuff
  }
});

Upvotes: 0

karim79
karim79

Reputation: 342635

That seems wasteful. Instead, just select the last item and act on it. E.g.:

$("td:last").hide();
$("p:last").hide();

Upvotes: 4

Related Questions