Roy Smith
Roy Smith

Reputation: 2165

Is there a way to set the entire content of a document?

I'm writing some unit tests with jest. I've captured the rendered HTML of some web pages in files and want to use those as data for my tests. I can load up the <body> of the saved HTML with:

const fs = require('node:fs');
html = fs.readFileSync('blah-blah-blah.body.html', 'utf8');
document.body.innerHTML = html;

which works, but it's annoying because while it's easy to get the full document with curl url -o blah-blah-blah.html, it's more complicated to post-process that to pull out just the <body> element. I tried the obvious thing:

html = fs.readFileSync('blah-blah-blah.document.html', 'utf8');
document.documentElement = html;

but apparently document.documentElement is read-only, so sadness.

Upvotes: 0

Views: 37

Answers (1)

Tushar Shahi
Tushar Shahi

Reputation: 20616

innerHTML property exists on all Elements. And document.documentElement returns an element. So you can just do the below

document.documentElement.innerHTML = '<html><head><title>TESTING</title></head><p>HELLO</p></html>'

Run this in your dev console and see this page disappear.

Upvotes: 0

Related Questions