27

I'm a guy used to mootools' way of chaining selectors, and I can't seem to find anywhere how to do the same in jQuery. Suppose I have a select element in the selectObj variable. What I need is to get the last option in that select. In mootools I would have done something like:

var option = $(selectObj).getElement('nth-child(last)')

Can I do something similar, or what is the way of getting that last option in jQuery?

PS. I know about the parent > child selector, but I can't really use it because I don't know what selector has been used to get the select. I only have the resulting element.

andi
  • 14,322
  • 9
  • 47
  • 46

4 Answers4

51
$(selectObj).find(':last')

You can use find to perform another query within the current query.

In general, you can check out the Selectors and Traversal pages on jQuery docs when you're trying to figure out how to select something.

bdukes
  • 152,002
  • 23
  • 148
  • 175
  • I only searched the "selectors" part of the doc and not the "traversing" one. I think cobbal's solution fits better though. – andi Mar 31 '09 at 13:17
  • 1
    This is the more general solution to the problem, and the one I was looking for when I searched and found this question. Thanks! – Pete Sep 24 '09 at 19:23
  • Just a quick aside, `.find` is one of the slowest selectors: http://jsperf.com/jquery-context-find-class. – dooburt Sep 09 '11 at 09:09
24
var option = $(selectObj).children(":last");

will return the last child of any element

cobbal
  • 69,903
  • 20
  • 143
  • 156
  • 3
    In fact most traversal operations in jQuery (siblings, find, parents, children, etc) allow an optional filter expression to be specified. – stusmith Mar 31 '09 at 12:51
  • This is what I've been looking for. I only searched the "selectors" part of the doc and not the traversing one. I don't know why though. Thanks. – andi Mar 31 '09 at 13:15
2

You can also use .last() for this purpose.

whoan
  • 8,143
  • 4
  • 39
  • 48
Alex Lapa
  • 1,149
  • 11
  • 21
0

jQuery has the :last Selector

$("tr:last").stuff()

Will do stuff to the last row in a table.

Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198