19

I've got an HTML string e.g. '<p><span class="text">Hello World!</span></p>'

I parse this HTML string to DOM using DOMParser().parseFromString(), because I want to change the innerHTML of some specific elements. That's why I parse the HTML string to DOM and with getElementByClassName I get all my elements and loop through them to change it innerHTML. This works so far.

After I changed the innerHTML, I try to convert the new DOM back to a string. I can't figure out how. What I tried is to assign the innerHTML or outerHTML (tried both) to a variable like this:

const parser = new DOMParser();
const doc = parser.parseFromString("<p>Hello World!</p>", "text/html");
console.log(doc.innerHTML) // undefined
console.log(doc.outerHTML) // undefined

const parser = new DOMParser();
const doc = parser.parseFromString("<p>Hello World!</p>", "text/html");
console.log(doc.innerHTML) // undefined
console.log(doc.outerHTML) // undefined

I always get undefined. How can I parse it back to a string? I found a lot examples with innerHTML or outerHTML, but in my case something went wrong. Any ideas?

1
  • You are missing () from the new DOMParser(). Should be (new DOMParser()).parseFromString(...) Commented Jul 17, 2019 at 11:30

1 Answer 1

34

DOMParser will always give you a document in return. Documents don't have an innerHTML property, but the document.documentElement does, just like in a page's normal document object:

const myHtmlString = '<p><span class="text">Hello World!</span></p>'
const htmlDom = new DOMParser().parseFromString(myHtmlString, 'text/html');
console.log(htmlDom.documentElement.innerHTML);

Do note that a <head> and <body> will be created for you, if you don't pass those tags in yourself. If you only want the body, then:

const myHtmlString = '<p><span class="text">Hello World!</span></p>'
const htmlDom = new DOMParser().parseFromString(myHtmlString, 'text/html');
console.log(htmlDom.body.innerHTML);

Sign up to request clarification or add additional context in comments.

3 Comments

Note that if you don't want the full document overhead, you can also just use a dummy "parent" element and assign its innerHTML value, a la let helper = document.createElement(`section`); helper.innerHTML = yourHTMLString; const domNode = helper.childNodes[0];.
Possible, but that can result in arbitrary code execution, unlike DOMParser.
Absolutely, never use this for user-generated content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.