AddEventListener is gone after adding innerHTML

Ok, so I have the following html added to the site using javascript / greasemonkey. (sample only)

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

and I also added a click event listener for the elements. Everything works fine up to this point, the click event is fired when I click on an item.

But ... I have another function in the script that, under a certain condition, modifies this html, i.e. he adds it, so it looks like this:

<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 will break the listeners that I added for the first two elements ... nothing happens when I click on them.

If I comment out the function call that adds, it all starts working again!

help me please...

+3
2

, innerHTML, HTML-, . ,

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

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

, , HTML, "", , , , . , HTML. - DOM, createElement appendChild:

var menu = pmgroot.getElementsByTagName("ul")[0];
var aEl  = document.createElement("a");
aEl.innerHTML = "Hello";
aEl.id "123";
menu.appendChild(aEl);
+10

U jQuery 'live'

0

Source: https://habr.com/ru/post/1742134/


All Articles