Pablo Pablo - 3 months ago 7
JSON Question

Getting index position of a div generated dinamically and stored in an array with a onclick function inside

I have two arrays, one contains all the divs generated and another one contains empty positions (later I fill them with a json). I need to find the exact position of the box I clicked so I can load also the exact position of the json array and edit it.

var counter = '';
var div = document.createElement('div');
div.className = 'new-box';
div.onclick = modifyBox;
document.getElementsByTagName('body')[0].appendChild(div);
boxStorage.push(div);
console.log(boxStorage)
boxContentStorage.push(counter);
console.log(boxContentStorage)


With var counter I add "" to each position so I always have the same size in the array of boxes and array of json. How can I return the index of each div I click so I can have control of the position in both arrays?

My code:

http://codepen.io/pablocgdev/pen/AXYkPG

Currently the button for modify isn't working as intended, when clicking a box and filling the fields you should edit that position of the json array, so box 1 is attached to json 1, box 2 to json 2...

Answer

Try this one, this will cast the DOM elements into an array and then will return the index of the clicked element

function getIndexOfDiv() {
   var divList = Array.prototype.slice.call(document.getElementsByClassName('new-box'));

   // pass the currently clicked div
   return divList.indexOf(this);
}