Home > Article > Web Front-end > How to Safely Append HTML Strings to the DOM Without Using `div.innerHTML = str;`?
Append HTML Strings to the DOM Without div.innerHTML
While appending HTML strings to the DOM using div.innerHTML = str; may be convenient, it is discouraged due to security vulnerabilities. A safer and more robust approach is to utilize the insertAdjacentHTML() method.
Using insertAdjacentHTML()
insertAdjacentHTML() offers a standardized way to insert HTML strings into the DOM. It takes two parameters:
In your case, to append the provided HTML string to the
<code class="javascript">const div = document.getElementById("test"); div.insertAdjacentHTML("beforeend", str);</code>
The "beforeend" position will insert the HTML inside the
Browser Compatibility
insertAdjacentHTML() is supported in all modern browsers, including Chrome, Firefox, Safari, and Edge.
Live Demo
For a demonstration, visit the following JSFiddle: http://jsfiddle.net/euQ5n/
The above is the detailed content of How to Safely Append HTML Strings to the DOM Without Using `div.innerHTML = str;`?. For more information, please follow other related articles on the PHP Chinese website!