0

How do you select the last child element in a known div where the child element is an unknown element. i.e: the element can be a paragraph or un-ordered list.

Most occasions the structure will be:

<div id="container">
<p>Text</p>
</div>

but on other occasions, the structure will be:

<div id="container">
<p>Text</p>
<ul>
<li>More Text</li>
</ul>
</div>
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
user3416023
  • 134
  • 1
  • 6

4 Answers4

3

You can use :last-child on its own without a type selector, like so:

$('#container > :last-child')

This is equivalent to specifying the * selector in place of a type selector (the * is optional and implied in this case, but you can put it in if it makes the code clearer to you):

$('#container > *:last-child')

This will get you the very last child regardless of what type of element it is. In your first structure, it's the p, and in the second structure, it's the ul (its li child is not included).

This is a valid CSS selector as well, so you can also use it in a stylesheet should you desire.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Standards-based selectors should be preferred. – cookie monster Mar 31 '14 at 07:52
  • @Shomz: I think so too, but I'm not familiar enough with `:first`, `:last` and `:eq()` to be sure, [because they work differently from standard CSS selectors](http://stackoverflow.com/questions/9983297/difference-between-css-selector-and-jquery-filter/10835694#10835694). I know for absolute certain that `:last-child` will work with the given markup, however. – BoltClock Mar 31 '14 at 07:53
  • Sure, sure, just saying... gave you +1 right away. :) – Shomz Mar 31 '14 at 07:54
2

You can use .last()

$('#container').children().last().show();
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
1

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

Use jQuerys last method on all div's children.

elrado
  • 4,960
  • 1
  • 17
  • 15
1

Use :last Selector

Try This

$('#container > :last')
Sridhar R
  • 20,190
  • 6
  • 38
  • 35