Getting content of an element as string with unescaped HTML

518 Views Asked by At

I'm using xmldom parser from npm library, it's based on the DOMNode object model. Having the following code:

var xml = "<p>Test</p><toFetch id="1">test\n\n<p>aaa</p>test\n</toFetch>";
var parser = new dom.DOMParser().parseFromString(xml, "text/xml");

I want to get the content of the toFetch tag, as a string with all unescaped HTML tags inside, and without the toFetch tag itself.

What I have is:

var elements = parser.getElementsByTagName("toFetch");
elements.forEach(element => {
    console.log(element.toString());
});

It works, but it gives me the string with toFetch surrounding tag. How can I get only the content?

1

There are 1 best solutions below

7
On

Your string has a typo in it. The 1 should be in single quotes, not doubles.

Then, change: console.log(element.toString());

To: console.log(element.textContent);