I am a beginner in JavaScript. A JavaScript book says that one of disadvantages of element.innerHTML
is:
Event handlers may no longer work as intended.
I can't understand what this mean. Can someone give me an example?
I am a beginner in JavaScript. A JavaScript book says that one of disadvantages of element.innerHTML
is:
Event handlers may no longer work as intended.
I can't understand what this mean. Can someone give me an example?
innerHTML
is a string representation of html contents of an element. Getting these contents has no side effect but resetting it force the browser to generate new elements.Each HTML tag in a document is parsed as an unique DOM HTMLElement object by the browsers. Event handlers are bound to these elements. By resetting
innerHTML
property, browser removes the old elements and makes the DOM parser to create other element objects based on the new html string. When an element is removed it's event handlers are also removed.Imagine that you have an element that responds to it's click events via a handler, when the element is removed you can't click on it so it makes you feel the handler is also removed. The way event handlers are garbage collected depends on the code that has been written and the way a JavaScript interpreter works.
Most probably, it refers to the technique some people use to insert HTML at the end:
This will get the current HTML, concatenate it with the inserted one, and parse it all.
As a side effect, all the internal state of the existing elements (like event listeners, checkedness, ...) will be lost.
Instead, if you want to insert some HTML at the end of an element, you can use
This will preserve the existing elements.
Another alternative, if you don't mind the inserted content to be wrapped inside an element, is using
appendChild
:Because when you dynamically create an element with Javascript with the element.innerHTML function, the newly created element might not respond to Event Listeners methods as intended.