Home > Article > Web Front-end > The difference between jquery selector :last and :last-child
Today I wrote $("ul li:last-child").offset().top and found an error, but $("ul li").last().offset().top just That’s right. The reason is:
Both selectors match the last element in the collection. The difference is that :last will match the last element in all collections. And :last-child will match all the last child elements in the collection. :last will always return one element, while :last-child may return a batch of elements.
So that’s it!
:last Selects the last matched element. Note that :last selects a single element by filtering the current jQuery collection and matching the last element within it. Additional Notes: Because :last is a jQuery extension and not part of the CSS specification, queries using :last cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :last to select elements, first select the elements using a pure CSS selector, then use.filter(":last").
:last-child:
Selects all elements that are the last child of their parent.
<div> <span>John,</span> <span>Karl,</span> <span>Brandon,</span> <span>Sam</span> </div> <div> <span>Glen,</span> <span>Tane,</span> <span>Ralph,</span> <span>David</span> </div> <script> $("div span:last-child") .css({color:"red", fontSize:"80%"}) .hover(function () { $(this).addClass("solast"); }, function () { $(this).removeClass("solast"); });
Both selectors are the last in the matching set element, the difference is that :last will match the last element in all sets. And :last-child will match all the last child elements in the collection. :last will always return one element, while :last-child may return a batch of elements.
$('div p:last') selects the last P element and highlights it. The result is as follows:
<div> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> </div> <div> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> </div> <div> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> </div>
$('div p:last-child') will select all Located at the last p sub-element of the div and highlighted:
<div> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> </div> <div> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> </div> <div> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> </div>
The above is the detailed content of The difference between jquery selector :last and :last-child. For more information, please follow other related articles on the PHP Chinese website!