Find Nth Element on a Page using jQuery

A lot of developers often ask how to find the Nth element on a Page – for eg: Check if the user clicked inside the ‘4th TextBox’ or Clicked the ‘3rd Link’ on a Page.

The answer to find the Nth element is using the jQuery eq() method which reduces the set of matched elements to the one at the specified index. Here’s an example:

Check if the 4th TextBox on the Page was clicked

$('input:text:eq(3)').click(function () {
alert('You clicked inside the 4th TextBox');
});

Check if the 3rd Link on the Page was clicked

$('a:eq(2)').click(function () {
alert('3rd Link was clicked');
});

Note: The supplied index in eq() is zero-based.

No comments:

Post a Comment