Reputation: 25032
I have taken a string of html
in and have converted it to a DOM Object
.
document.getElementById("textarea").value
var parser = new DOMParser();
var html = parser.parseFromString(htmlString, 'text/html');
How do I take the DOM Object
that I created and convert it back to html
? Could you please show an example how I could put it on an html
page?
Upvotes: 3
Views: 8123
Reputation: 123473
From the HTMLDocument
that parseFromString()
gives you, you can retrieve the its documentElement
and then that element's innerHTML
.
console.log(html.documentElement.innerHTML);
Note that the markup may become normalized to make it a valid document, so you may end with more than you started:
var markup = '<span>Foo</span>';
var parser = new DOMParser();
var doc = parser.parseFromString(markup, 'text/html');
console.log(doc.documentElement.innerHTML);
// "<head></head><body><span>Foo</span></body>"
Or, have corrections made for you:
var markup = '<table><div>Foo</div></table>';
// ...
console.log(doc.documentElement.innerHTML);
// "<head></head><body><div>Foo</div><table></table></body>"
Upvotes: 4
Reputation: 729
You seem to be creating an entire Document, not sure if that is intentional. But, this should work with that you have now:
var parser = new DOMParser();
var html = parser.parseFromString('<b>ok</b>', 'text/html');
document.write(html.body.innerHTML);
Upvotes: 1