1

So I am using innerHTML to create paragraphs and then attach event handlers to them in a loop. In the end the event fires only on the last paragraph, while the previous ones dont respond to the click at all.

Also, I tried to generate the paragraphs using DOM methods too(meaning createElement, appendChild, etc), and everything worked just fine. So I would really appreciate if anyone explained what is wrong with this approach(using innerHTML).

The code:

window.onload=function(){
function a(){
    alert(this.innerHTML);
}
for(var i= 0; i<10; i++){
    document.body.innerHTML+="<p>Paragraph: "+i+"</p>";
    document.getElementsByTagName('p')[i].addEventListener('click', a, false);
}
}

Edit

So i ran a proper test and turns out that rather than saying the event listeners arent attached, actually they are attached and "detached" in the next loop.

Also working version using DOM manipulation:

window.onload=function(){
/* Works when creating paragraphs using DOM methods. */
        function a(){
        alert(this.innerHTML);
    }
for(var i= 0; i<10; i++){
    var p= document.createElement("p");
    var txt= document.createTextNode("Paragraph: "+i);
    p.appendChild(txt);
    document.body.appendChild(p);
    document.getElementsByTagName('p')[i].addEventListener('click', a, false);
}
}
user3398216
  • 93
  • 1
  • 5

0 Answers0