jQuery API

:first Selector

first selector

version added: 1.0jQuery(':first')

Description: Selects the first matched element.

The :first pseudo-class is equivalent to :eq(0). It could also be written as :lt(1). While this matches only a single element, :first-child can match more than one: One for each parent.

Additional Notes:

  • Because :first is a jQuery extension and not part of the CSS specification, queries using :first cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :first to select elements, first select the elements using a pure CSS selector, then use .filter(":first").
  • Selected elements are in the order of their appearance in the document.

Example:

Finds the first table row.

<!DOCTYPE html>
<html>
<head>
  <style>

  td { color:blue; font-weight:bold; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <table>
    <tr><td>Row 1</td></tr>
    <tr><td>Row 2</td></tr>

    <tr><td>Row 3</td></tr>
  </table>
<script>$("tr:first").css("font-style", "italic");</script>

</body>
</html>

Demo:

Support and Contributions

Need help with :first Selector or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to :first Selector? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • hc

    If you know there is only one element to be found, is it faster (in terms of performance) to use ':first' as part of the selector or not?

    For example, if your markup is this:

    <table> <tbody><tr><td>Row 1</td></tr></tbody></table>

    And you want to get the first row, and you know there will always only be one row, is it faster to do:

    $('table > tr')

    or

    $('table > tr:first')

    Has anyone done speed tests to verify the answer?

    • milesslow

      Maybe your example is overly simplified, but in this situation, aren't there are a lot more important questions than performance? For example, will there ever be more than one row in this table? If so, do you want this selector to apply to only the first row, or all rows in the table? Will this row /always/ be the first row? Will someone create a row and put your row in a (which will break your selector in two separate ways as far as selecting the intended row)? Will there ever be more than one table on the page? What if that table occurs before yours in the page?

      • http://powerlord.livejournal.com/ R Bemrose

        I would still stick to the version with the :first selector, as it somewhat future proofs things.

        In fact, to REALLY future proof it, perhaps it should be:
        $('table > tbody > tr:first')
        This is assuming any table headers ( tags) would be in a

        • hc

          Wow, I shouldn't have given an example, as people seem to focus on that instead of the actual question about performance. The table example was for illustrative purposes only. Obviously it's not real. What's the point of a table with only one row?

          My question is, when you have a selector (any selector), that you know will only return one element, is the jQuery processing faster if you explicitly include “:first”. My inclination is that “:first” would be faster, because as it travels the DOM looking for matches, it stops as soon as it finds one, whereas a selector WITHOUT “:first” would have to continue looking for matches even if ultimately there is only one match. But that's just my hunch, and it'd be nice if someone could definitively say which is true, preferably with performance statistics. I guess I'll have to do some measurements myself.

          • milesslow

            If performance is your only concern, and you know the selector is only going to match one element, then YES, use the ':first' selector. The truth is, $('tr:first') is either going to be a lot faster than $('tr'), or negligibly slower. If it bothers you not knowing for sure, then please take a stab at reading through Sizzle, and let us know what you find out.

          • Chris

            I did a test using firebugs console.time, and doing a $('.blah') vs. $('.blah:first'), with no :first the test came back 0 ms, and with :first it took 4 ms, then putting both of those in a loop and ran each 1 thousand times, no first was on the order of a hundred ms, while first was on the order of 1000 ms. So doing :first does not actually stop the query from checking the rest of the dom, so you are better off not doing :first, at least until browsers and js are smart enough to stop checking the dom.

  • Noor

    These are considered unknown sudo selectors in firefox. They do work but they throw CSS errors…which is nasty. And btw, simply disabling CSS errors in firefox is just ignoring the fact that this is not supported

    • http://www.learningjquery.com/ Karl Swedberg

      But since they are being used as arguments of JavaScript functions, not as actual CSS pseudo-selectors, the Firefox error console has no business reporting them as CSS errors. I agree that it's nasty. Maybe report the bug on bugzilla? https://bugzilla.mozilla.org/

  • Jeremy

    Using first in theory should be much faster but in practice it can be quite a bit slower. Try this:
    console.time('loop'); for(var i=0; i<1000; i++){$('div');} console.timeEnd('loop');
    vs this:
    console.time('loop'); for(var i=0; i<1000; i++){$('div:first');} console.timeEnd('loop');

    On one page I am working on the second takes twice as long. Weird.

    • milesslow

      Wow, you're right. I guess I was forgetting that computers don't understand the semantics of the ':first' selector. They treat it like any other position selector, which I think are processed at the very end (consider the ':last' selector, which can only be processed after all matching elements are found). That's what I get from glancing at the sizzlejs source. Honestly, it doesn't matter if it takes twice as long (three times on my page), because it takes < 1ms for either selector, and if you ever use a position selector 1000 times in a row, you should be using a better data structure than an html document.

    • MrBester

      FWIW:
      console.time('loop'); for(var i=0; i<1000; i++){$('div').eq(0);} console.timeEnd('loop');
      is only 7.5% slower than not specifying the index, but including ':first' nearly doubles the time taken. At least it does on a simple example page I'm using to test. If every ns counts then speciying the index is the way to go, unless someone feels like forking Sizzle to short-circuit the ':first' selector. No, didn't think so…

  • Benjamin H Kohl

    Why are people so concerned about milliseconds? If you have to use any tools to measure the difference in performance of these various selectors, then the difference is negligible. When you buy a box of cereal, do you take it home and check to make sure the box contains the exact number of ounces that is displayed on the box? Unless you are obsessive, you probably don't. I have ever executed some JQuery and said to myself, “That is 14ms of my life I wish I had back.”

  • Roger Proctor

    simple question more to with firebug console debugger why does :first get identified as unknown pseudo-class

  • Chris

    I did a test using firebugs console.time, and doing a $('.blah') vs. $('.blah:first'), with no :first the test came back 0 ms, and with :first it took 4 ms, then putting both of those in a loop and ran each 1 thousand times, no first was on the order of a hundred ms, while first was on the order of 1000 ms. So doing :first does not actually stop the query from checking the rest of the dom, so you are better off not doing :first, at least until browsers and js are smart enough to stop checking the dom.