Please tell onclick why the onclick event in the code below is not executed. If you remove the last line with innerHTML , everything works:

 var div = document.createElement('div'); div.innerHTML = "Default message"; div.onclick = function(){this.innerHTML = 'Onclick message'} document.body.appendChild(div); document.body.innerHTML += 'Next line'; 

    1 answer 1

    Any change to the innerHTML property results in a complete replacement of all elements.

    So after doing

     document.body.innerHTML += 'Next line'; 

    the div element to which the handler has been added has been removed, and now a new div is instead replaced by the handler.

    To solve, you can either collect the entire line at once, and only then hang handlers

     var div = `<div id="div">Default message</div>`; document.body.innerHTML += div; document.body.innerHTML += 'Next line'; document.getElementById('div').onclick = function() { this.innerHTML = 'Onclick message' } 

    or do not use innerHTML , but create elements directly:

     var div = document.createElement('div'); div.innerHTML = "Default message"; div.onclick = function() { this.innerHTML = 'Onclick message' } document.body.appendChild(div); var textNode = document.createTextNode('Next line'); document.body.appendChild(textNode); 

    An alternative way to add markup, as suggested in the comments , is to use the insertAdjacentHTML method.

     var div = document.createElement('div'); div.innerHTML = "Default message"; div.onclick = function() { this.innerHTML = 'Onclick message' } document.body.appendChild(div); div.insertAdjacentHTML('afterEnd', 'Next line'); 

    • In general, everything is strangely done. Logically, it should not replace everything, but simply add a new line to the existing code. Invalid language :) - Yuri
    • 3
      @Yuri, nothing to do with the language, this is working with the DOM. It was done exactly according to the logic: innerHTML is all HTML , after its assignment it must be parsed again and rendered, which is what happens. - Grundy
    • Is it possible to somehow save all the functions of all the elements before replacing, and then again the same elements?) - Yuri
    • @Yuri, added solutions. - Grundy
    • Well, I know these decisions. But if you have already assigned all the functions and in the process of working with the site, the innerHTML changes. Is it possible to somehow pick up all the events before recording, and then re-assign? I know that you can write the assignment of events in a function and then call it. - Yuri