Ludo
Ludo

Reputation: 5280

How to get a jQuery item in a collection of selectors

I would like to access a selector in my array:

<ul>
  <li class="elem">A</li>
  <li class="elem">B</li>
  <li class="elem">C</li>
</ul>

var $elems = $('li.elem');
console.log($elems[1].text()); /* jQuery method call */

I know there is the get() method, but it seems to be an implementation to se [] operator. So what is the best way to access an item on a jQuery array?

Should we do something like $($elems[1]).text() ?

Upvotes: 0

Views: 68

Answers (4)

rab
rab

Reputation: 4144

You could try followings ways

// jQuery Method call 
console.log( $($elems[1] ).text() ); 
console.log( $elems.filter(':eq(1)').text() );
console.log( $elems.eq(1).text() );

//native method
console.log( $elems[1].innerHTML );

All prints same results

Upvotes: 0

Dogbert
Dogbert

Reputation: 222428

Use method for get text .eq

$('li.elem').eq(1).text();

Upvotes: 3

RRikesh
RRikesh

Reputation: 14411

You can use eq()

$(document).ready(function(){
  var $elems = $('li.elems');
  console.log( $elems.eq(1).text() );
});

You should note that get() returns a DOM element while eq() returns a jQuery object.

Upvotes: 0

palaѕн
palaѕн

Reputation: 73966

You can simply do this using the eq() method:

var $elems = $('li.elems');
console.log($elem.eq(0).text());

Since, eq() is zero based index, so eq(0) will give you the first li in the collection.

Upvotes: 0

Related Questions