0

I wrote this script to add elements to the DOM according to content stored in an array, then I added a listener on a click event to those elements.

It works, but I am pretty sure it can be improved, any idea?

function writeSuggestions() {
  for (var k = 0; k < suggestions.length; k++) {
    citySample.innerHTML += "<li>" + suggestions[k][0] + "</li>";
  }

  for (var i = 0; i < citySample.children.length; i++) {
    (function(index){
      citySample.children[i].onclick = function(){
        lat = suggestions[index][1];
        lng = suggestions[index][2];
      };
    })(i);
  }
}

Thank you in advance

KevinO
  • 4,303
  • 4
  • 27
  • 36
  • You have an XSS vulnerability. – SLaks Apr 26 '18 at 15:14
  • Concatenating to `innerHTML` is very slow. – SLaks Apr 26 '18 at 15:14
  • Placing the event handler on the parent element is a common method for targeting dynamically created children: https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements/27373951#27373951 – ericArbour Apr 26 '18 at 15:23
  • @SLaks, tks for your answer, can you tell me how to solve the vulnerability ? And how to improve performence with `innerHTML` ? –  Apr 27 '18 at 13:16

0 Answers0