SHARE
TWEET

innerHTML and outerHTML getter implementation

Witiko May 29th, 2012 133 Never
  1. // Call like this:
  2. //   html(element);       - retrieves the innerHTML of an element
  3. //   html(element, true); - retrieves the outerHTML of an element
  4.  
  5. var html = (function() {
  6.   var ELEMENT = this.Node?Node.ELEMENT_NODE:1,
  7.          TEXT = this.Node?Node.TEXT_NODE:   3;
  8.   return function html(el, outer) {
  9.     var i = 0, j = el.childNodes, k = outer?"<" + (m = el.nodeName.toLowerCase()) + attr(el) + ">":"",
  10.         l = j.length, m, n;
  11.     while(i !== l) switch((n = j[i++]).nodeType) {
  12.       case ELEMENT: k += html(n, true); break;
  13.       case TEXT:    k += n.nodeValue;
  14.     } return k + (outer?"</" + m + ">":"");
  15.   }; function attr(el) {
  16.     var i = 0, j = el.attributes, k = new Array(l = j.length), l, m;
  17.     while(i !== l) k[i] = (m = j[i++].nodeName) + "=\"" + el.getAttribute(m) + "\"";
  18.     return (l?" ":"") + k.join(" ");
  19.   }
  20. })();
RAW Paste Data
Top