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.

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: