jquery
  1. jquery-eq

Understanding jQuery eq()

The jQuery eq() method allows you to select a specific element based on its index within a set of matched elements. This can be useful for selecting elements based on their position in the DOM, rather than their class or ID.

Syntax

Here is the basic syntax for using the jQuery eq() method:

$(selector).eq(index)
  • selector: The element(s) to select.
  • index: The zero-based index of the element to select.

Use

The eq() method is useful for selecting a specific element within a set of matched elements. For example, you might use it to select the second or third element in a list, or to select an element based on its position within a parent element.

Example

Here is an example of how to use the eq() method to select the third paragraph element on a webpage:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery eq() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
    $(document).ready(function(){
        $("p").eq(2).css("background-color", "yellow");
    });
    </script>
</head>
<body>
    <h1>My Webpage</h1>
    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>
    <p>This is the third paragraph.</p>
    <p>This is the fourth paragraph.</p>
</body>
</html>
Try Playground

In this example, we use the eq() method to select the third paragraph (<p>) element on the webpage and use jQuery's css() method to change its background color to yellow.

Summary

The jQuery eq() method is a powerful tool for selecting specific elements based on their position within a set of matched elements. Whether you need to select the first, second, or nth element in a list, or a specific element within a parent element, the eq() method provides an easy and effective way to do so.

Published on: