Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index element in list with jQuery

Tags:

jquery

<ul>
  <li>Kelvin</li>
  <li>Jerry</li>
  <li>Adi</li>
  <li>Dani</li>
  <li>Olvin</li>
</ul>

How to get the index of the <li> element that contains "Jerry"?

I've tried to read these

  • http://api.jquery.com/jQuery.each/
  • http://api.jquery.com/index/

But can't find the answer :( Can you help me with that?

like image 332
Arie Prasetyo Avatar asked Mar 09 '12 07:03

Arie Prasetyo


People also ask

How to get the index of element in jQuery?

To access the index of an element in jQuery, use the eq() method. The eq() method refers the position of the element.

What is get () in jQuery?

In jQuery . get() method loads data from the server by using the GET HTTP request. This method returns XMLHttpRequest object. Syntax.

What is EQ jQuery?

Definition and Usage. The :eq() selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). This is mostly used together with another selector to select a specifically indexed element in a group (like in the example above).

How do I get DOM element?

The easiest way to find an HTML element in the DOM, is by using the element id.


2 Answers

Using jQuery's .index will give you the index of an element in the given elements:

var index = $('li').index($('li:contains("Jerry")'));
like image 110
Joakim Johansson Avatar answered Nov 14 '22 06:11

Joakim Johansson


Somewhat more efficiently:

var jerry = $('li:contains("Jerry")');
var jerry_index = jerry.siblings().index(jerry);
like image 44
Candide Avatar answered Nov 14 '22 07:11

Candide