2

I would like to change some text in my body html with code below. Replacing works fine, but after that it seems to stuck, can't get out of function, so next parts of my script cannot be executed.

Nothing will happen after clicking .another-button. I think problem is with line that change body.innerHTML because when I delete this line everything works fine.

$(".do-replace-button").on("click", function () {
    //some different code
    document.body.innerHTML = document.body.innerHTML.replace(regExp, newWord);
}

$(".another-button").on("click", function (event) {
    //some code that won't execute
}
zazini
  • 21
  • 2
  • You're using `innerHTML` in the body so wen the first event executes, all the other handlers are removed. [Manipulating innerHTML removes the event handler of a child element?](https://stackoverflow.com/questions/5113105/manipulating-innerhtml-removes-the-event-handler-of-a-child-element) – Gerardo Jul 23 '17 at 00:26

2 Answers2

1

You are effectively replacing the innerHTML of your <body> with something else, which is a string, the result of your replace(). That string is parsed and built into new DOM elements and the old ones are getting replaced by the new ones.

Hence, the events you bound on the old ones are gone, because the elements are gone. One way to solve this would be to:

a) bind on document itself:

$(document).on('click', '.do-replace-button', function() {
  // whatever...
})

b) find another, less aggressive way to achieve whatever it is you are achieving with that replace.

Do note it's not only your events that get removed, but any event bound by any library/plugin you might have loaded and already initialized by the time your script runs. I strongly recommend against running replace on innerHTML, especially on <body>.

tao
  • 82,996
  • 16
  • 114
  • 150
0

The call to document.body.innerHTML and the right hand assignment that comes after it is completely replacing the html inside the document, or more specifically, the parser is building a completely new node tree inside the body so all of your HTMLElement nodes that may have previously had event listeners assigned to them are no longer there. I recommend you go another route of only replacing the the HTML that matches your regex instead of the entire HTML contents of the body element. Or you could have a function that is called inside the first event-listener callback that fires after the replacement of the body HTML, that will re-initialize the event listeners.