Skip to content
Advertisement

How to disable parsing code in script tags using JavaScript DOMParser?

I have the following text file with JavaScript tags:

<script>
...
</script>
<script>
...
</script>
<script>
...
</script>

when I parse it like so:

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(`<root>${data}</root>`, "text/xml");
const tags = xmlDoc.getElementsByTagName("script");

I get an error because there are < and > symbols in JS program code, like

for (let i = 0; i < tags.length; i++) {

I don’t want to replace < > with &lt; &gt; because those are also present inside strings in the code.

Is it possible to disable parsing code inside script tags?

Advertisement

Answer

For parsing HTML, we use the mime type text/html

const htmlDoc = parser.parseFromString(data, "text/html");
const tags = htmlDoc.getElementsByTagName("script");
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement