webta.st.ic
webta.st.ic

Reputation: 5169

Parse HTML String to DOM and convert it back to string

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?

Upvotes: 19

Views: 23520

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370659

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);

Upvotes: 34

Related Questions