I need to know the index of clicked element. Can\'t figure out how to do it
for (i = 0; i < document.getElementById(\'my_div\').children.length; i++) {
With ES6 destructuring you can do
const index = [...el.parentElement.children].indexOf(el)
or
const index = Array.from(el.parentElement.children).indexOf(el)
or ES5 version
var index = Array.prototype.slice.call(el.parentElement.children).indexOf(el)
I made a function to find the index.
function index(el) {
return [...el.parentElement.children].indexOf(el);
}
Call it like this:
let index = index(element);
getIndexOfNode: function(node){
var i = 1;
while(node.previousElementSibling != null){
i++
}
return i;
}
the function will return the index of the node passed in its parent element.