Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS eventListener click disappearing

Tags:

javascript

I created simple fidlle

var cnt = 1;
function add() {
    var root = document.getElementById('root')    
    root.innerHTML += '<br /><a id= "a_' +cnt + '" href="#">click</a>'
    var a = document.getElementById("a_"+cnt)
    a.addEventListener('click', function(event) {
        alert('click:a_'+cnt)
    })
    cnt++
}

When Add button is clicked once new link is added and after clicking on this link alert appears.

When more links are added with Add button only the last link works(others does not have click event listener according to devel tools).

Why does only the last link work and how can I make all links working?

like image 267
Joe Avatar asked Dec 10 '22 13:12

Joe


2 Answers

Because you are reinserting the anchor tags in the html. The question is similar to Appending HTML string to the DOM.

You can use

root.insertAdjacentHTML( 'beforeend', '<br /><a id= "a_' +cnt + '" href="#">click</a>');

instead of

root.innerHTML += '<br /><a id= "a_' +cnt + '" href="#">click</a>'

Working fiddle https://jsfiddle.net/0nm4uLvd/

Just to improve answer, here is another reference why event listeners are removed when dom element is removed => If a DOM Element is removed, are its listeners also removed from memory? thanks to these guys :)

like image 120
Sachin G. Avatar answered Dec 24 '22 21:12

Sachin G.


You're modifying the innerHTML of your root element. This will cause the complete 'root' to be destroyed en recreated, so only the new event will work.

See Manipulating innerHTML removes the event handler of a child element?.

like image 43
Tom Drissen Avatar answered Dec 24 '22 20:12

Tom Drissen