Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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)

Solution 2:

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
    }
    returnthis === parent.children[i] ? i : -1;
}

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

JS Fiddle demo.

References:

Solution 3:

Solution 4:

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.

Solution 5:

the expanded version (jquery) would be

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

Post a Comment for "How To Find The Position For An Element In A Li With Jquery Or Vanilla Js"