rafaelleru rafaelleru - 24 days ago 8
HTML Question

Set onClick property of HTML element into for loop

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);
})
}
}


`

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