I’m failing to parse a XML document embedded in a script
tag with Vanilla JavaScript:
document.addEventListener('DOMContentLoaded', function() {
const xmlStr = document.getElementById('xml').innerText;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlStr,'text/xml');
const barText = xmlDoc.getElementById('bar').textContent;
alert(barText)
});
<body>
<h1>Parsing <script type="text/xml"> with JavaScript</h1>
<script id="xml" type="text/xml">
<?xml version="1.0" encoding="utf-8"?>
<foo>
<bar id="bar">Hello world!</bar>
</foo>
</script>
</body>
What’s the problem here?