How to get element order number
how can i get order number of some element by javascript/jquery?
<ul>
<li>Anton</li>
<li class="abc">Victor</li>
<li class="abc">Simon</li>
<li>Adam</li>
<li>Peter</li>
<li class="abc">Tom</li>
</ul>
There is 3xli with abc class. Now I need to g开发者_高级运维et order(sequence) number of Simon li.
Thanks in advance
With Jquery's index() method
You can do it like this using a selector with .index()
, like this:
$('li:contains(Simon)').index('.abc'); //returns 1, it's 0 based
//Or this...
$('li').filter(':contains(Simon)').index('.abc'); //returns 1
Without the selector, you'd get 2
, the index of the <li>
in the parent overall, regardless of the class. You can view a quick demo here. Keep in mind it's a 0 based index, may need to + 1
the result for display in some cases, depends what you need it for.
For those of you who prefer You Might Not Need Jquery approach, here is the method:
function index(el) {
if (!el) return -1;
var i = 0;
do {
i++;
} while (el = el.previousElementSibling);
return i;
}
IE8 and less:
function index(el) {
if (!el) return -1;
var i = 0;
do {
if (el.nodeType === 1) i++;
} while (el = el.previousSibling)
return i;
}
Just a fix for the @Nick Craver answer. I tried using .index('.class_name')
and that kept on returning -1 for a not found. What I did then was .index( $('.class_name') )
which gave me the intended result. I guess it requires a dom node object for it's value and not just a selector.
精彩评论