JavaScript Gets a New Set of HTML Insertion APIs
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:
const container = document.querySelector('#comments');
container.insertAdjacentHTML(
'beforeend',
'<p>Thanks for the update!</p>'
);
The first argument tells the browser where the HTML should be inserted. In this case, beforeend means that the new content should be added as the last child of the element.
It works perfectly fine, but the API relies on positional strings to describe what should happen.
The new methods take a more direct approach. Instead of passing a position as an argument, you get a separate method for each insertion operation.
For instance, the equivalent operation using the new API looks like so.
const container = document.querySelector('#comments');
container.appendHTML('<p>Thanks for the update!</p>');
Much easier to read, no?
There are six methods available for inserting or replacing HTML:
| Method | What it does |
|---|---|
setHTML() |
Replaces the contents of an element |
appendHTML() |
Adds HTML as the last child |
prependHTML() |
Adds HTML as the first child |
beforeHTML() |
Inserts HTML before an element |
afterHTML() |
Inserts HTML after an element |
replaceWithHTML() |
Replaces the element with new HTML |
For example, if you want to add a notification at the beginning of a container, you can simply use prependHTML().
const notifications = document.querySelector('#notifications');
notifications.prependHTML(`
<div class="notification">
Your changes have been saved.
</div>
`);
Similarly, if you want to replace the contents of an element altogether, you can use setHTML().
The idea is fairly simple: the method name itself tells you what will happen to the existing content.
HTML insertion with sanitization built in
There’s another interesting aspect of these methods.
The regular HTML insertion methods use the browser’s default sanitizer. This means potentially unsafe HTML is removed according to the default sanitization rules before it is inserted into the document.
For instance:
const container = document.querySelector('#content');
container.setHTML(`
<h2>Welcome</h2>
<script>alert('Hello!')</script>
<p>This is some content.</p>
`);
The browser sanitizes the supplied HTML before inserting it. Elements considered unsafe by the sanitizer, such as script elements, are not retained.
This is particularly useful when you’re working with HTML that may contain untrusted content.
However, there are situations where you may need more control over the sanitization process. The API also allows you to supply a custom Sanitizer.
const sanitizer = new Sanitizer({
elements: ['em', 'i', 'b', 'strong']
});
container.setHTML(
'<p>Hello <strong>there</strong>!</p>',
{ sanitizer }
);
Here, we’re using a custom sanitizer that allows only the specified elements.
There’s also an Unsafe variant for each of these methods, such as setHTMLUnsafe() and appendHTMLUnsafe().
As the name suggests, these methods don’t apply the default sanitizer automatically. They can also accept a custom sanitizer and support an optional runScripts setting, which is false by default.
For example:
container.setHTMLUnsafe(
'<p>This is some content.</p>',
{ runScripts: true }
);
This gives developers more control when they have a specific reason to insert HTML without the default sanitization or to execute scripts included in the markup.
Of course, the Unsafe methods should be used carefully, particularly when the HTML comes from an untrusted source.
Streaming HTML directly into the DOM
This is probably the most interesting part of the new APIs.
Traditionally, when you fetch some HTML using JavaScript, you usually wait for the entire response to arrive before inserting it into the document.
For example:
const response = await fetch('/api/comments.html');
const html = await response.text();
container.appendHTML(html);
This works, but it means the browser has to wait until the complete response is available before it can insert anything.
The new streaming methods allow you to insert HTML as it arrives instead.
Each of the insertion methods has a corresponding streaming variant:
| Regular method | Streaming method |
|---|---|
setHTML() |
streamHTML() |
appendHTML() |
streamAppendHTML() |
prependHTML() |
streamPrependHTML() |
beforeHTML() |
streamBeforeHTML() |
afterHTML() |
streamAfterHTML() |
replaceWithHTML() |
streamReplaceWithHTML() |
For instance, you can stream an HTML response directly into an element like so:
const container = document.querySelector('#comments');
const response = await fetch('/api/comments.html');
await response.textStream().pipeTo(
container.streamAppendHTML()
);
Here, textStream() provides the response body as a stream of decoded text. We then pipe that stream directly into streamAppendHTML().
The browser can process and insert the HTML incrementally instead of waiting for the entire response to finish downloading.
This can be useful when you’re dealing with large content updates or when the server is generating HTML progressively.
You can also use the standard Streams API directly with TextDecoderStream if you need more control over how the response is processed:
const response = await fetch('/api/content.html');
response.body
.pipeThrough(new TextDecoderStream())
.pipeTo(container.streamAppendHTML());
There’s also a streaming Unsafe variant, such as streamAppendHTMLUnsafe(), when you need the behaviour provided by the unsafe insertion methods.
Browser support
These APIs are part of Chrome’s Declarative Partial Updates work and are being added to the HTML platform.
The newer insertion and streaming methods are available in recent Chromium releases, but they aren’t supported across all browsers yet. So, if you’re planning to use them, it’s worth checking for support before relying on them.
You can use feature detection like this:
if ('appendHTML' in Element.prototype) {
container.appendHTML('<p>Hello!</p>');
} else {
container.insertAdjacentHTML(
'beforeend',
'<p>Hello!</p>'
);
}
Chrome has also released an html-setters-polyfill for developers who want to use the API shape in browsers that don’t support it natively.
One thing worth noting is that the polyfill doesn’t reproduce the native streaming behaviour. It buffers the content and applies it once the complete content is available.
So, it can help with compatibility for regular insertion methods, but it doesn’t provide the same benefit as native streaming.
In Closing
I think this is a nice addition to the browser platform (even though the support is still limited). We’ve had several ways to insert HTML using JavaScript for quite some time, but they have come with slightly different APIs and behaviours.
These new methods make the intention behind an operation much clearer. You can tell whether you’re appending, replacing, or streaming HTML just by looking at the method name.
The streaming part is particularly interesting because it brings some of the benefits of HTML’s streaming nature to content inserted through JavaScript.
It’s a small change, but one that makes a fairly common operation in frontend development a little more straightforward and consistent.
👋 Hi there! This is Amit, again. I write articles about all things web development. If you enjoy my work (the articles, the open-source projects, my general demeanour... anything really), consider leaving a tip & supporting the site. Your support is incredibly appreciated!