Home > Web Front-end > JS Tutorial > How to Safely Append HTML Strings to the DOM Without Using `div.innerHTML = str;`?

How to Safely Append HTML Strings to the DOM Without Using `div.innerHTML = str;`?

Mary-Kate Olsen
Release: 2024-11-05 07:13:02
Original
988 people have browsed it

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:

  • position: Specifies where to insert the HTML relative to the target element. Can be "beforebegin," "afterbegin," "beforeend," or "afterend."
  • html: The HTML string to insert.

In your case, to append the provided HTML string to the

with the ID "test," you can use the following code:

<code class="javascript">const div = document.getElementById("test");
div.insertAdjacentHTML("beforeend", str);</code>
Copy after login

The "beforeend" position will insert the HTML inside the

, after its last child.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template