Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
128
rated 0 times [  135] [ 7]  / answers: 1 / hits: 18238  / 8 Years ago, sat, february 13, 2016, 12:00:00

How exactly do I get the index of e.target? IndexOf wont work and I dont want to use the Array.prototype property. So what is the best way to get the index of the target element?



Basically element is a container with a bunch of divs. If I hover over a div I want to get its index.



element.addEventListener(mouseover, someEvent, false);


function someEvent(e) {
if (e.target !== e.currentTarget) {
// get the index of the hovered element here
}
e.stopPropagation();
}


I explicitely stated that I dont want to use Array.prototype so the link is not a duplicate.



By the way, here a jsfiddle https://jsfiddle.net/nbjve593/


More From » javascript

 Answers
197

As the mouseover event doesn't have an index property and you don't want to use Array.prototype methods, here is an alternative





var els = document.querySelectorAll('#container-id div');

for(i=0; i < els.length; i++) {

els[i].index = i;

els[i].addEventListener('mouseover', function(e) {

e.target.innerHTML = e.target.index;

}, false);
}

#container-id div {
background: yellow;
margin: 10px;
height: 20px;
}

<div id=container-id>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>





Update



If you have thousands of child elements you might want Array.prototype.indexOf anyway.



This version use children instead of childNodes, to avoid getting all the text nodes.





var el = document.getElementById('container-id');

el.addEventListener('mouseover', function(e) {

var p = e.target.parentElement;
var index = Array.prototype.indexOf.call(p.children, e.target);

if (e.target !== el) {
e.target.innerHTML = index;
}

}, false);

#container-id div {
background: yellow;
margin: 10px;
height: 20px;
}

<div id=container-id>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>





Initial source: Finding DOM node index


[#63328] Wednesday, February 10, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pranavrorys

Total Points: 466
Total Questions: 87
Total Answers: 115

Location: Barbados
Member since Sun, Nov 27, 2022
2 Years ago
pranavrorys questions
Fri, May 27, 22, 00:00, 2 Years ago
Thu, Oct 28, 21, 00:00, 3 Years ago
Sat, May 30, 20, 00:00, 4 Years ago
Fri, Dec 20, 19, 00:00, 5 Years ago
;