how to get nth jquery element

how to get nth jquery element  using -'jquery'

asked Sep 24, 2015 by sameer rathore
0 votes
1 view

7 Answers

0 votes

You can use the :eq selector, for example:

$("td:eq(2)").css("color", "red"); // gets the third td element

Or the Traversing/eq function:

$("td").eq(2).css("color", "red");

Also, remember that the indexes are zero-based.

answered Sep 24, 2015 by sameer rathore
0 votes

if you have control over the query which builds the jQuery object, use :eq()


If you don't have control over it (for example, it's being passed from another function or something), then use .eq()

var $thirdElement = $jqObj.eq(2);

Or if you want a section of them (say, the third, fourth and fifth elements), use .slice()

var $third4th5thElements = $jqObj.slice(2, 5);
answered Sep 24, 2015 by ankitarajoria4
0 votes

I think you can use this

$("ul li:nth-child(2)").append(" - 2nd!");

It finds the second li in each matched ul and notes it.

answered Sep 24, 2015 by patelnikul321
0 votes

.eq() -An integer indicating the 0-based position of the element. Ex:

Consider a page with a simple list on it:

  • list item 1
  • list item 2
  • list item 3
  • list item 4

We can apply this method to the set of list items:

$( "li" ).eq( 2 ).css( "background-color", "red" );

For more information : .eq()

answered Sep 24, 2015 by tseetha
0 votes

For iterations using a selector doesn't seem to make any sense though:

var some = $( '...' );

for( i = some.length -1; i>=0; --i )
   // Have to transform in a jquery object again:
   var item = $( some[ i ] );

   // use item at will
   // ...
answered Sep 24, 2015 by param.oncemore
0 votes

Live Example to access and remove the Nth element with jQuery:

    " rel="nofollow" target="_blank">">
  1. First
  2. Second
  3. Third

When it runs, there are two items in the ordered list that show, First, and Third. The second was hidden.

answered Sep 24, 2015 by suyesh.lokhande
0 votes

If you already have the jquery object in a variable, you can also just treat it as a normal indexed array, without the use of jquery:

var all_rows = $("tr");
for(var i=0; i < all_rows.length; i++){
   var row = all_rows[i];
   //additionally, you can use it again in a jquery selector

Although the above example is not useful in any way, it is representing how you can treat objects created by jquery as indexed arrays.

answered Sep 24, 2015 by gauravg.gwl