Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!

innerHTML and outerHTML getter implementation

By: Witiko on May 29th, 2012  |  syntax: JavaScript  |  size: 0.84 KB  |  views: 93  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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. })();