Reputation: 10684
I was curious as to why:
$("div.title").last();
does not return the same item as the css code:
$("div.title:nth-child(0)")
or $("div.title:last-child")
im trying to reference it in css, but it seems that it doesnt seem to do it.
the html looks like:
<div>
<div class="title"></div>
<div></div>
<div class="title"></div>
<div></div>
</div>
Upvotes: 0
Views: 77
Reputation: 3268
:last-child
only applies to the last child of the parent (similar to the jQuery .last()
)
However, the CSS :last-of-type
selects the last occurrence of the pattern, which is probably what you were aiming to do:
div.title:last-of-type
will select the same element as the jQuery $("div.title").last();
(note: both of these selectors do not work by default in IE8 or lower)
Upvotes: 1
Reputation: 2666
The reason is that in CSS, :last-child
refers to the last child of the parent. So for..
<div>
<div class="title"></div>
<div></div>
<div class="title"></div>
<div></div>
</div>
div.title:last-child
will not select anything as the last child of div.title
's parent is a div
.
:nth-child(n)
works with the same logic. Here n
refers to the index of each child of the parent starting the count from 1
.
last()
of jQuery is different. It selects the last occurrence of the jQuery selector that has been provided. So, $("div.title").last();
will select the last div.title
in the entire code.
Upvotes: 0
Reputation: 967
:last-child
in CSS will only select the element if it is the last child of it's parent, regardless of element, class, or any other selector.
In jQuery .last()
will actually filter on the collection of elements you got in your jQuery selector.
Upvotes: 6