-1

I'm trying to push in mi html a list of files name, passing it by argument. in the function I iterate over the files with a for loop and create a nuew 'li' element with document.createElement('li'), then I try to add a property onclick to each item, and I want that onclick call a function with the value thaht i has in the create of element.

my code looks like: `

function(files){
    for(var i=0; i < files.length; i++){
        var list_element = document.createElement('li');
        list_element.setAttribute('id', 'item_'+ i.toString());

        //set onclick property
        (function(i){
            list_element.onclick = functionToCallInOnClick(i);
        })
    }
}

` how I can set this property tho every li element?

rafaelleru
  • 367
  • 1
  • 2
  • 19
  • 1
    You need to call your anonymous function immediately in your for loop. See [here](http://stackoverflow.com/questions/19586137/addeventlistener-using-for-loop-and-passing-values). – Stephan Genyk Oct 22 '16 at 18:06

2 Answers2

2
//set onclick property
(function(i){
    list_element.onclick = function () {
        functionToCallInOnClick(i);
    };
})(i);
1

There is one mistake in your code you are missing one ending bracket. )

 list_element.setAttribute('id', 'item_'+ i.toString() );
Asad Mukhtar
  • 391
  • 6
  • 18