Reputation: 51
is there any way to get index of clicked div in parent div?
Here's an example:
<div class="parent">
<div id="1" class="child"></div>
<div id="2" class="child"></div>
<div id="3" class="child"></div>
<div id="4" class="child"></div>
</div>
<script>
var parent = document.getElementsByClassName("parent");
var child = document.getElementsByClassName("child");
for(var i=0; i < parent.length; i++){
parent[i].addEventListener("click", function(e){
console.log(e.target)
console.log(e.target.parentNode)
});
}
</script>
What I mean is, is there any way to get index of clicked div? For example, if I would click div with id "1", it would print "0" in console since its index is 0. If I would click div with id "2", it would print "1" in console since its index is 1, and so on.
Is there any way to do this? (without using attributes)
Upvotes: 1
Views: 3480
Reputation: 44202
Use Array.prototype.indexOf()
to find the child inside it's parent.children
var child = document.getElementById('findme');
var parent = child.parentNode;
var index = Array.prototype.indexOf.call(parent.children, child);
console.log(index);
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child" id="findme"></div>
<div class="child"></div>
</div>
Using ES6 Array.prototype.findIndex()
;
var child = document.getElementById('findme');
var parent = child.parentNode;
var index = Array.prototype.findIndex.call(parent.children, (c) => c === child);
console.log(index);
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child" id="findme"></div>
<div class="child"></div>
</div>
However, this could give some issues on eg IE.
Upvotes: 0