6

Okay, so i have the following html added to a site using javascript/greasemonkey. (just sample)

<ul>
 <li><a id='abc'>HEllo</a></li>
 <li><a id='xyz'>Hello</a></li>
</ul>

and i've also added a click event listener for the elements. All works fine up to this point, the click event gets fired when i click the element.

But... i have another function in the script, which upon a certain condition, modifies that html, ie it appends it, so it looks like:

<ul>
 <li><a id='abc'>Hello</a></li>
 <li><a id='xyz'>Hello</a></li>
 <li><a id='123'>Hello</a></li>
</ul>

but when this is done, it breaks the listeners i added for the first two elements... nothing happens when i click them.

if i comment out the call to the function which does the appending, it all starts working again!

help please...

Gert Cuykens
  • 6,845
  • 13
  • 50
  • 84
Vishal Shah
  • 3,774
  • 4
  • 23
  • 25
  • You problem is probably in your javascript. Can you paste that here so we can see what's going on? – Jage Apr 21 '10 at 17:04
  • the function that appends new html is : var menu = pmgroot.getElementsByTagName("ul")[0]; menu.innerHTML += (its long so i din't bother to put it here) – Vishal Shah Apr 21 '10 at 17:10

3 Answers3

21

Any time you set the innerHTML property you are overwriting any previous HTML that was set there. This includes concatenation assignment, because

element.innerHTML += '<b>Hello</b>';

is the same as writing

element.innerHTML = element.innerHTML + '<b>Hello</b>';

This means all handlers not attached via HTML attributes will be "detached", since the elements they were attached to no longer exist, and a new set of elements has taken their place. To keep all your previous event handlers, you have to append elements without overwriting any previous HTML. The best way to do this is to use DOM creation functions such as createElement and appendChild:

var menu = pmgroot.getElementsByTagName("ul")[0];
var aEl  = document.createElement("a");
aEl.innerHTML = "Hello";
aEl.id "123";
menu.appendChild(aEl);
Andy E
  • 338,112
  • 86
  • 474
  • 445
-1

As an variant, you can add such html, which will work without addEventListener:

<ul>
 <li><a id='abc' onclick='myFunc()'>Hello</a></li>
 <li><a id='xyz' onclick='myFunc()'>Hello</a></li>

 // The following add dynamically
 <li><a id='123' onclick='myFunc()'>Hello</a></li>
</ul>
Dmitry Shashurov
  • 1,148
  • 13
  • 11
-3

U can also use jQuery's 'live' function

Abhishek Mehta
  • 1,447
  • 1
  • 14
  • 16