Technology1 min read

JavaScript Gets a New Set of HTML Insertion APIs

By · Published by Everything Blog

In short

Browsers such as Chrome and Edge are rolling out a suite of methods designed to streamline inserting and streaming HTML into the DOM. This framework replaces older approaches like `insertAdjacentHTML()` with dedicated functions like `setHTML()`, `appendHTML()`, and `replaceWithHTML()`. By default, these operations employ the browser's native sanitizer to automatically strip dangerous elements like scripts prior to document insertion. Developers can also pass a custom `Sanitizer` instance to define precise element allowlists based on application needs.

Key points

  • Web developers gain descriptive, dedicated alternatives to replace legacy positional stri…: Web developers gain descriptive, dedicated alternatives to replace legacy positional string methods like `insertAdjacentHTML()`.
  • Integrated browser sanitization helps safeguard web applications from malicious markup wi…: Integrated browser sanitization helps safeguard web applications from malicious markup without requiring third-party libraries.
  • The `Unsafe` method variants provide developers explicit control over script execution an…: The `Unsafe` method variants provide developers explicit control over script execution and custom sanitization rules.

Sources checked by our analysis pipeline: 1

There are several ways to insert HTML into a web page using JavaScript. You can use innerHTML

, insertAdjacentHTML()

, createContextualFragment()

, or even the relatively newer setHTML()

method.

They all get the job done, but they don’t necessarily behave in the same way. Some replace existing content, some append it, and some provide built-in HTML sanitization. If you want to stream HTML into an element, things get a little more complicated.

Chrome (and Edge) is trying to bring some consistency to this with a new set of HTML insertion and streaming methods. These methods provide a more descriptive way to insert HTML into an existing element, along with the ability to stream content directly into the DOM.

Let’s see how these methods work and how they compare to the existing ones.

- A more consistent way to insert HTML

- HTML insertion with sanitization built in

- Streaming HTML directly into the DOM

- Browser support

- In Closing

A more consistent way to insert HTML

If you’ve used insertAdjacentHTML()

before, you’d probably be familiar with something like this:

Technology