GibboK
GibboK

Reputation: 73908

How to find the position for an element in a li with jquery or vanilla js

Lets imagine I have the following HTML code.

I need to find the position within the LI elements for the LI which has the class focus applied.

In this example the result should be 2 (if at 0 index). Any idea how to do it?

<ul class="mylist">
    <li>Milk</li>
    <li>Tea</li>
    <li class="focus">Coffee</li>
</ul>

Upvotes: 2

Views: 1668

Answers (5)

David Thomas
David Thomas

Reputation: 253308

While you've already accepted an answer to your question, I thought I'd put together a simple index() method for HTMLElements:

HTMLElement.prototype.index = function () {
    var self = this,
        parent = self.parentNode,
        i = 0;
    while (self.previousElementSibling){
        i++;
        self = self.previousElementSibling
    }
    return this === parent.children[i] ? i : -1;
}

var focus = document.querySelector('li.focus'),
    i = focus.index();
console.log(i); // 2

JS Fiddle demo.

References:

Upvotes: 3

Florian
Florian

Reputation: 3366

In jQuery, you should be able to get it, via index. With classes, you could run into issues, when having multiple of them.

I prepared a Plunker, where you can see a solution to the problem.

Upvotes: 1

Lab
Lab

Reputation: 1063

the expanded version (jquery) would be

$(document).ready(function(){
 $('li').each(function(){
  var cls=$(this).attr('class');
  if(cls=='focus'){
   alert($(this).index());
  }
 });
});

Upvotes: 0

Anton
Anton

Reputation: 32581

Use .index()

var index = $('.focus').index();

DEMO

Specific list

$('.mylist .focus').index()

DEMO

Upvotes: 2

rid
rid

Reputation: 63442

In pure JavaScript:

var index = 0;
var lis = document.getElementsByTagName('li');
for (var len = lis.length; index < len; ++index) {
    if (lis[index].className.match(/\bfocus\b/)) {
        break;
    }
}

(fiddle)

Upvotes: 4

Related Questions