user798080
user798080

Reputation:

Get innerHTML without using innerHTML

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

Answers (3)

swannty
swannty

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

maerics
maerics

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

Šime Vidas
Šime Vidas

Reputation: 185873

I think you want this:

someElement.textContent

Upvotes: -1

Related Questions