YouTip LogoYouTip

Sel Eq

## jQuery :eq() Selector The `:eq()` selector in jQuery is used to select an element with a specific index number. It allows you to target a precise element from a matched set of elements based on its position. --- ## Definition and Usage The `:eq()` selector selects an element based on its zero-based index. * **Zero-based Indexing:** The index value starts at `0`, meaning the first element has an index of `0`, the second has an index of `1`, and so on. * **Common Use Case:** It is most frequently used in combination with other selectors (such as element, class, or ID selectors) to target a specific element within a group (e.g., selecting the second paragraph in a document). --- ## Syntax ```javascript $(":eq(index)") ``` ### Parameter Values | Parameter | Description | | :--- | :--- | | `index` | **Required.** Specifies the index of the element to select. It can be a positive or negative integer. | > **Note:** If a negative number is provided, it counts backward from the last element in the selected set (e.g., `:eq(-1)` selects the very last element). --- ## Code Examples ### Example 1: Selecting the Second Paragraph The following example demonstrates how to select and style the second `

` element (index `1`) in a document. ```html

This is the first paragraph (index 0).

This is the second paragraph (index 1).

This is the third paragraph (index 2).

``` ### Example 2: Using Negative Indexing You can pass a negative integer to target elements starting from the end of the matched set. ```javascript // Selects the second-to-last paragraph in the document $("p:eq(-2)").css("font-weight", "bold"); ``` --- ## Considerations and Best Practices ### 1. Performance Alternative: `.eq()` Method While the `:eq()` pseudo-class selector is highly convenient, it is a jQuery extension and not part of the CSS specification. Because of this, queries using `:eq()` cannot take advantage of the performance boost provided by the native DOM `querySelectorAll()` method. For optimal performance, especially in large documents, it is recommended to use the jQuery `.eq()` method instead: ```javascript // Instead of this: $("p:eq(1)").css("background-color", "yellow"); // Use this for better performance: $("p").eq(1).css("background-color", "yellow"); ``` ### 2. CSS3 Alternative: `:nth-child()` If you prefer to stick to standard CSS selectors, you can use the `:nth-child()` selector. However, keep in mind that `:nth-child()` is **1-based**, whereas `:eq()` is **0-based**. ```javascript // These two statements target the same element: $("p:eq(1)"); // jQuery 0-based index (2nd element) $("p:nth-child(2)"); // Standard CSS 1-based index (2nd element) ```
← Sel GtSel Parent Child β†’