3
 <div id="main">
  <div class="1"></div>
  <div class="2"></div>
  <div class="2"></div>
  <div class="3"></div>
  <div class="3"></div>
  <div class="4"></div>
 </div>

How we can write a selector using :last-child in jquery to find out the last div with class 3 ?

1

4 Answers 4

11

Try this selector... though your classes shouldn't be just numbers. They should start with a normal character.

$("#main .3:last")

FYI, :last-child checks if the target is last child of its parent. None of the elements with class .3 are the last child of their parent.

4
  • -1 Direct child selector doesn't work an all current (microsoft) browsers. Jun 13, 2012 at 8:40
  • 2
    @MihaiStancu care to show a jsfiddle of that? jsfiddle.net/eyvb6/1 is working fine for me in ie7. There is also no direct child selector here.
    – Esailija
    Jun 13, 2012 at 8:40
  • @MihaiStancu I'm still curious about the direct child bug in IE, since jQuery does somewhat patch querySelectorAll in some areas. Can you demonstrate it?
    – Esailija
    Jun 13, 2012 at 8:45
  • Tested, couldn't replicate in a Windows VM, with up to date upgrades. Perhaps my recollections are from olden times (jQuery 1.2 -ish). Cant revert the downvote unless you edit your answer. Jun 13, 2012 at 8:50
3

Use .last():

$("#main .3").last();

http://api.jquery.com/last/

http://jsfiddle.net/E64Wm/1/

0

$('#main > .3').last() should point to the right element

-5

Try this:

$('#main').find(':last-child');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.