Cover Image for jQuery eq() method
107 views

jQuery eq() method

The eq() method in jQuery is used to select a specific element from a collection of elements based on its index. It allows you to retrieve a single element from a set of matched elements by providing the zero-based index of the element you want to select.

The syntax for using the eq() method is as follows:

$(selector).eq(index);
  • selector: It is a string that specifies the elements to be selected.
  • index: An integer value representing the zero-based index of the element you want to retrieve from the collection. If the index is negative, it counts from the end of the collection.

Here’s an example of how you can use the eq() method:

HTML:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

JavaScript:

// Select the second <li> element (index 1)
var secondItem = $('li').eq(1);

// This will return a jQuery collection containing the second <li> element (Item 2).

// Select the last <li> element (index -1, same as :last selector)
var lastItem = $('li').eq(-1);

// This will return a jQuery collection containing the last <li> element (Item 5).

The eq() method is particularly useful when you want to perform operations on a specific element within a collection of matched elements without having to use traditional JavaScript array indexing. Keep in mind that eq() returns a jQuery collection even if it selects a single element, so you can continue chaining other jQuery methods after using eq(). If you need to access the raw DOM element from the collection, you can use array indexing or retrieve it using the [0] property of the jQuery collection.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS