How to replace the content of an element using HTMLRewriter


I am writing a script that replaces the content of an element with new (static) text.

Nothing fancy.

I am new to working with Workers and HTMLRewriter. I have written a small script but having trouble getting it to work.

Here’s what I am trying to do:

When a user requests a page on my website, I’d like the worker to replace the content of the element " with new content.

The content is static, and I store it in a variable “default_header” in my script.

When I run this script, the HTML that goes back to the user almost works. The problem is that the new content of the header element is HTML-escaped, and therefore breaks the formating of the page.

What am I missing?

Here is the script (I have removed most of the default_header content to make it fit easily in this post):

const default_header = `<header id="masthead" class="site-header"><div class="container site-header-container flex default-header"> </div></header>
class HeaderRewriter


const rewriter = new HTMLRewriter()
.on(‘header[id=“masthead”]’, new HeaderRewriter())

async function handleRequest(req)
const res = await fetch(req);
return rewriter.transform(res);

addEventListener(‘fetch’, event => {

Simply pass { html: true } as second argument in your replace call and HTML should not be escaped.

One other thing, header#masthead might be more idiomatic as selector.

Thank you Sandro, that worked well.