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.

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: