Search code examples
javascriptjqueryjquery-selectorscss-selectorspseudo-class

":last-of-type" or ".last()" when using JQuery


:last-of-type (as of v1.9) vs .last() (as of v1.4): Either method works, but can anyone tell me which is the better method based on efficiency?

Example:

$(".item").last();

$(".item:last-of-type");

".last()" has been around longer (as of v1.4). Does JQuery have ":last-of-type" built-in, or is it just utilizing CSS and piggybacking on the browser's capability? Can anyone confirm this?

It would seem to me that ":last-of-type" would be better when applicable if this is the case.


Solution

  • .last() is faster.

    Note, the selectors perform different selections

    :last-of-type

    last-of-type selector

    Description: Selects all elements that are the last among siblings of the same element name.

    .last()

    .last()

    Description: Reduce the set of matched elements to the final one in the set.

    console.time("lastOfType");
    $(".item:last-of-type");
    console.timeEnd("lastOfType");
    
    console.time("last");
    $(".item").last();
    console.timeEnd("last");
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>