Javascript - Dynamically generated event handlers not working(when using innerHTML)

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

Answers


The problem is this line:

document.body.innerHTML+="<p>Paragraph: "+i+"</p>";

Basically, this takes the stringified HTML from the body and appends a string on to it. Then, it sticks a new string back into the body. That string is then parsed as HTML. Since it is only a string being inserted into the body, none of the elements that are parsed have eventListeners attached.

The last <p> tag is not affected because the HTML of the body is not changed afterwards.

The DOM manipulation works because well, as the name suggests, it is specifically made for this.


Need Your Help

Switch values of comboboxes for priority sorting table in HTML? How do I fix my code?

php javascript html

I would like to make a table wherein the headers have priorities placed in comboboxes. I want it so that when I change the priority of a combobox, the other combobox that holds that number will swi...

WinForms databinding and foreign key relationships

c# .net winforms

I'm developing a WinForms application (.Net 3.5, no WPF) where I want to be able to display foreign key lookups in a databound DataGridView.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.