The Perils of Element.innerHTML =
Appending HTML content to an element using element.innerHTML = ... may seem like a convenient shortcut, but it can lead to performance issues and unexpected behavior.
Why it's Bad Code
When you assign a new value to element.innerHTML, the existing HTML is completely replaced. This triggers a browser re-parse of the entire subtree, which can be costly if the element contains a significant amount of complex HTML. The re-parsing can:
Alternatives to innerHTML =
Instead, use appendChild() to append a new element to the end of an existing element. For instance:
var newElement = document.createElement('div'); newElement.innerHTML = '<div>Hello World!</div>'; element.appendChild(newElement);
This approach ensures that the existing HTML is preserved and no re-parsing occurs.
Optimization Note
Some browsers may have optimizations that prevent re-parsing when using innerHTML =. However, it's best to avoid this practice for consistency and performance reasons.
The above is the detailed content of Why Is Using `element.innerHTML =` Considered Bad Practice?. For more information, please follow other related articles on the PHP Chinese website!