If i click the a element "Link1" e.target in the function is the node Link1. I want to know in what index this node is in the ul children in this case i want indexOf to return 0 because Link1 is on position 0, and i i click 2 i want it to be 1.
HTML
<div class="link">
<ul>
<li><a>Link1</a></li>
<li><a>Link2</a></li>
</ul>
</div>
JAVASCRIPT
self.query('.link').forEach(function(linkNode, flikIndex, flikArr) {
dojo.query(linkNode, 'click', function(e) {
var t = e.target; //If i click Link1 this is Link1 and if i click Link2 and so on.
var parent = t.parentNode; //Contains the parent to my a in this case li
var ancestor = t.parentNode.parentNode.childNodes; //Containes 2 li
var index = Array.prototype.indexOf.call(parent, ancestor); //Return -1 but i want it to return 0 because Link1 is on place [0] in the array.
}
}
Please help me get the right index
If i click the a element "Link1" e.target in the function is the node Link1. I want to know in what index this node is in the ul children in this case i want indexOf to return 0 because Link1 is on position 0, and i i click 2 i want it to be 1.
HTML
<div class="link">
<ul>
<li><a>Link1</a></li>
<li><a>Link2</a></li>
</ul>
</div>
JAVASCRIPT
self.query('.link').forEach(function(linkNode, flikIndex, flikArr) {
dojo.query(linkNode, 'click', function(e) {
var t = e.target; //If i click Link1 this is Link1 and if i click Link2 and so on.
var parent = t.parentNode; //Contains the parent to my a in this case li
var ancestor = t.parentNode.parentNode.childNodes; //Containes 2 li
var index = Array.prototype.indexOf.call(parent, ancestor); //Return -1 but i want it to return 0 because Link1 is on place [0] in the array.
}
}
Please help me get the right index
Share Improve this question asked Jun 18, 2013 at 11:23 rubinrubin 6972 gold badges7 silver badges12 bronze badges 1-
3
I suspect you want
Array.prototype.indexOf.call(ancestor, parent)
– apsillers Commented Jun 18, 2013 at 11:25
2 Answers
Reset to default 6var index = Array.prototype.indexOf.call(parent, ancestor);
// ^ Array ^ Element in the array
So you want this:
var index = Array.prototype.indexOf.call(ancestor, parent);
Since ancestor
is the element ("array") that contains parent
.
Try this:
let nodes = Array.from( parent.closest('ul').children);
let index = nodes.indexOf(li);
When we work with a NodeList, getting the index of the li can be tricky using this approach:
var ancestor = t.parentNode.parentNode.childNodes;
var index = Array.prototype.indexOf.call(ancestor, parent);
If we have text in the lis, then these are also considered childNodes, and so the index of the li which is returned will be its index in the nodeList which consists of other children such as text, and not merely other lis. Therefore, you may not be getting the desired result in case you are only interested in the position of an li relative to the other lis in the ul