Reputation:
I know innerHTML
is supposed to be icky (and let's not start a debate. We're trying to phase it out at my work), but I need to be able to get the plaintext version of some HTML. Right now I have the lines...
bodycontents = document.getElementById("renderzone").innerHTML;
But I am wondering exactly how I would, say, get the same result WITHOUT innerHTML
. I am not afraid of DOM manipulation (I've done a ton of it), so please feel free to be as technical in your answer as you need to be.
Upvotes: -1
Views: 3158
Reputation: 151
On modern browser the XMLSerializer
may help you:
var el = document.getElementById('my-id');
var html_string = new XMLSerializer().serializeToString(el);
console.log(html_string);
<p id="my-id">Greetings Friends</p>
Upvotes: 0
Reputation: 156374
Retrieving an elements inner HTML content without using the element.innerHTML
attribute sounds like an academic pursuit that isn't likely to have a simple solution.
A DOM based approach would require something like recursively walking to retrieve all child nodes and append their text content and serialize the element name and attributes. For example (in JavaScript/DOM pseudo-code):
var getHtmlContent(el, str) {
str += '<' + el.nodeName;
foreach (attr in el.attribute) {
str += attr.name + '="' + escapeAttrVal(attr.value) + '"';
}
str += '>';
foreach (node in el.childNodes) {
if (node.isTextNode()) {
str += node.textContent;
} else {
str += getHtmlContent(node, str);
}
}
str += '</' + el.nodeName + '>';
return str;
}
getHtmlContent(myElement, ''); // '<div id="myElement" class="foo">Text<div...'
Upvotes: 2