Home > Article > Web Front-end > Why is using `element.innerHTML = \"...\"` a bad practice?
The Perils of Appending with Element.innerHTML
You've heard whispers that concatenating elements using element.innerHTML = "..." is a coding no-no. But what exactly is the harm in it?
Consider the following snippet:
var str = "<div>hello world</div>"; var elm = document.getElementById("targetID"); elm.innerHTML += str; // Not recommended?
The issue lies in the repeated parsing and rendering of the HTML. Whenever innerHTML is assigned, the browser must parse the HTML, construct the DOM, and insert it into the document. This process is time-consuming and can become especially laborious for complex HTML structures.
As a result, using innerHTML = for simple appending of elements is discouraged. Instead, opt for the appendChild method:
var newElement = document.createElement('div'); newElement.innerHTML = '<div>Hello World!</div>'; elm.appendChild(newElement);
By using appendChild, you avoid unnecessary re-parsing and maintain the integrity of the existing DOM elements.
Note: While some browsers may optimize the = operator, it's best not to rely on this behavior for performance optimization.
The above is the detailed content of Why is using `element.innerHTML = \"...\"` a bad practice?. For more information, please follow other related articles on the PHP Chinese website!