JoeS
JoeS

Reputation: 1425

How to get the last element within several elements?

If I have the following HTML:

 <div>
  <span></span>
  <span>I want this one</span>
 </div>
 <div>
  <span></span>
  <span>I want this one</span>
 </div>

How can I get the last two spans?

If I do this $('div').find('span:last') or $('div').find('span').last() then I only get the last one?

Thanks,

Joe

Upvotes: 0

Views: 65

Answers (2)

ramchauhan
ramchauhan

Reputation: 238

Working example is here
http://jsfiddle.net/S298c/9/

$('div').each(function(){
   var lastspantext = $(this).find('span:last-child').html();
   alert(lastspantext);
});

Upvotes: 2

ProllyGeek
ProllyGeek

Reputation: 15836

$("div span:last-child")

will return an array though ! with all matches , so better use .each()

 $("div span:last-child").each(function( index ) {
  //your actions
});

Upvotes: 5

Related Questions