Reputation: 43
Is that possible to append a html file to Jsdom which already been loaded with a seperate html file?
Upvotes: 0
Views: 1620
Reputation: 174
The other answers replace the body's inner html. The OP wants to append:
Dependencies:
npm install jsdom
Solution:
const {JSDOM} = require("jsdom");
const fs = require("fs");
const appendJSDOM = (dom, htmlFile) => {
const html = fs.readFileSync(htmlFile).toString();
dom.window.document.body.insertAdjacentHTML('beforeend', html);
}
JSDOM.fromFile("file1.html")
.then(dom => {
appendJSDOM(dom ,"file2.html");
console.log(dom.serialize());
});
You can keep calling appendJSDOM()
to append more html files. But like the other answers have said you should omit the <html>
, <head>
, and <body>
tags in the additional html files.
insertAdjacentHTML can also insert HTML in different places depending on what you put as the first argument.
Upvotes: 2
Reputation: 45
I think this one will help.
require('jsdom-global')();
var fs = require('fs');
document = window.document;
var dashboard =
fs.readFileSync('yourHtmlFile').toString();
document.documentElement.innerHTML = dashboard;
Upvotes: 1
Reputation: 17661
Yes, you can do that. The simplest approach would be to:
jsdom
.fs
.jsdom
.Install
npm install jsdom --save-dev
npm install fs --save-dev
Example code:
var jsdom = require('jsdom').JSDOM;
var fs = require('fs');
var document = (new jsdom('<!DOCTYPE html><html><head></head><body></body></html>')).window.document;
var secondHtml = fs.readFileSync('HelloWorld.html').toString();
document.body.innerHTML = secondHtml;
Note that your second HTML should exclude <html>
, <head>
and <body>
tags. Otherwise you'll have problems with a <body>
tag inserted inside an existing <body>
tag.
Upvotes: 1