YouTip LogoYouTip

Sel First

## jQuery :first Selector The `:first` selector is a built-in jQuery filter used to select the **very first** element that matches a given query from the matched set of DOM elements. --- ## Definition and Usage The `:first` selector filters the matched set of elements and returns only the first one in the document order. * **Single Element Selection:** This selector always returns a single element (or zero if no matches are found). * **Difference from `:first-child`:** While `:first` selects only the single first element of the entire matched set, the [`:first-child`](sel-firstchild.html) selector can select multiple elements (the first child of *each* parent element). * **Complementary Selector:** To select the last element of a matched set, use the [`:last`](sel-last.html) selector. --- ## Syntax ```javascript $(":first") ``` Most commonly, it is combined with another selector to target the first element of a specific type or class: ```javascript $("selector:first") ``` --- ## Code Examples ### Example 1: Basic Usage Select and style the first `

` element on the page: ```javascript $(document).ready(function(){ // Selects the first

element in the entire document $("p:first").css("background-color", "yellow"); }); ``` ### Example 2: Selecting the First Element in a List Select the first list item (`

  • `) inside an unordered list: ```html
    • First item (Will be selected)
    • Second item
    • Third item
    ``` --- ## Comparison: `:first` vs. `:first-child` It is crucial to understand the difference between these two selectors to avoid unexpected layout behaviors. | Selector | Description | Result | | :--- | :--- | :--- | | **`$("p:first")`** | Selects the **absolute first** `

    ` element on the entire page. | Only **one** element is ever selected. | | **`$("p:first-child")`** | Selects every `

    ` element that is the **first child** of its respective parent container. | **Multiple** elements can be selected if they are first-born children in different containers. | ### Live Comparison Example Consider the following HTML structure: ```html

    Paragraph 1 (First child of Container 1)

    Paragraph 2

    Paragraph 3 (First child of Container 2)

    Paragraph 4

    ``` * Running `$("p:first")` will target **only** `Paragraph 1`. * Running `$("p:first-child")` will target **both** `Paragraph 1` and `Paragraph 3`. --- ## Performance Tip 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. For optimal performance in modern browsers, you can use the standard CSS selector `:first-child` or use jQuery's `.eq(0)` method instead: ```javascript // Alternative high-performance approach $("p").eq(0).css("background-color", "yellow"); ```
  • ← Sel LastSel Multiple Elements β†’