javalsai
javalsai

Reputation: 41

How to run the scripts in html document and get resulting document in node?

I have a string in node with a html document like this:

<p id="text">First text</p>
<script>
    document.getElementById('text').innerHTML = 'Second text';
</script>

And I want to get the resulting html document after running the scripts like this:

<p id="text">Second text</p>
<script>
    document.getElementById('text').innerHTML = 'Second text';
</script>

I don't know how to do it and I didn't found anything that can help. The scripts are more complex, this is an example

Upvotes: 1

Views: 594

Answers (1)

Sanskar Bansal
Sanskar Bansal

Reputation: 188

You can look for a package called JSDOM.

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const dom = new JSDOM(`<p id="text">First text</p>
<script>
    document.getElementById('text').innerHTML = 'Second text';
</script>
`, { runScripts: "dangerously" }
); 

console.log(dom.window.document.body.innerHTML); 

You can check more details regarding this package on this url: https://www.npmjs.com/package/jsdom

Upvotes: 1

Related Questions