Home  >  Article  >  Web Front-end  >  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
Mary-Kate OlsenOriginal
2024-11-05 07:13:02890browse

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>

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!

Statement:
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