Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  36] [ 3]  / answers: 1 / hits: 22738  / 12 Years ago, sat, december 1, 2012, 12:00:00

As per the jQuery api, the complementary operation to .get(), which accepts an index and returns a DOM node, .index() can take a DOM node and returns an index. Suppose we have a simple unordered list on the page:



<ul>
<li id=foo>foo</li>
<li id=bar>bar</li>
<li id=baz>baz</li>
</ul>


.index() will return the position of the first element within the set of matched elements in relation to its siblings:



alert('Index: ' + $('#bar').index();


We get back the zero-based position of the list item:



Index: 1


I just want to know, how can we do the same using JavaScript??


More From » jquery

 Answers
26

You can build your own function :



function indexInParent(node) {
var children = node.parentNode.childNodes;
var num = 0;
for (var i=0; i<children.length; i++) {
if (children[i]==node) return num;
if (children[i].nodeType==1) num++;
}
return -1;
}


Demonstration (open the console)


[#81675] Friday, November 30, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trayvon

Total Points: 35
Total Questions: 117
Total Answers: 88

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;