- Home
- Forum
- JavaScript - EJ 2
- Mention what is the disadvantage of using inner HTML in JavaScript?
Mention what is the disadvantage of using inner HTML in JavaScript?
The use of inner HTML in JavaScript has the following disadvantages −
There is no append support without reparsing the whole innerHTML. This makes changing innerHTML directly very slow.
For example, for appending to an HTML tag, you'll need to do the following −
let myDiv = document.querySelector('#myDiv')
// Reparses the whole myDiv tag.
myDiv.innerHTML += '<p>Added new tag</p>'innerHTML does not provide validation and therefore we can potentially insert valid and broken HTML in the document and break it.
The innerHTML property is extremely popular because it provides a simple way to completely replace the contents of an HTML element. Another way to do that is to use the DOM Level 2 API (removeChild, createElement, appendChild) but using innerHTML is by far the easiest and most efficient way to modify the DOM tree. However, innerHTML has few problems of its own that you need to be aware of:
- Content is replaced everywhere : When you append to (or otherwise modify) innerHTML, all the DOM nodes inside that element have to be re-parsed and recreated.
- Preserves event handlers attached to any DOM elements : Setting innerHTML will not automatically reattach event handlers to the new elements it creates, so you would have to keep track of them yourself and add them manually, potentially creating a memory leak on some browsers.
- Even if you use +=like "innerHTML = innerHTML + 'html'" still the old content is replaced by html: String concatenation just does not scale when dynamic DOM elements need to be created as the plus' and quote openings and closings becomes difficult to track.
- 9 Replies
- 5 Participants
-
ZI Zinavo
- Feb 27, 2021 11:40 AM UTC
- Mar 16, 2021 05:34 AM UTC