13

I want to print the entire element including tag name, attribute name/value pairs and innerHTML. How can I do it in JavaScript (jQuery)?

for example:

var elArr = document.getElementsByTagName('link');
alert(elArr[0].printEntireElement());

//expected output might be 
<link href="/css/common.css" rel="stylesheet" type="text/css">`

Note that for link element outerHTML is not defined!

Anthony Forloney
  • 90,123
  • 14
  • 117
  • 115
celicni
  • 420
  • 3
  • 7
  • 16

5 Answers5

7

Use an outerHTML jQuery plugin, like this one, or this one.

Ben S
  • 68,394
  • 30
  • 171
  • 212
  • Damn, I did it (http://dbj.org/dbj/?p=91) but it seems so inefficient ... But I can't think of anything better, still ? –  Apr 09 '13 at 18:51
2

If you can't do outerHtml, clone it, create a new div, place the clone in the div, and grab the innerHTML of the container.

Yuliy
  • 17,381
  • 6
  • 41
  • 47
  • See http://stackoverflow.com/questions/867916/creating-a-div-element-in-jquery to create a div in jquery. :) – Steropes Oct 05 '11 at 20:25
1

If you want to print an entire tag from a jQuery element you could do something like this:

var el = $('<div id="my_div">test div 123</div>');

alert(el[0].outerHTML);
BlueStory
  • 235
  • 2
  • 4
1
document.getHTML= function(who){
    var txt, ax, el= document.createElement("div");
    el.appendChild(who.cloneNode(false));
    txt= el.innerHTML;      
    ax= txt.indexOf('>')+1;
    txt= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);
    el= null;
    return txt.replace(/>/g,'>\n');
}
kennebec
  • 102,654
  • 32
  • 106
  • 127
0

you can do something like this:

function dump(element) {
  var a = ["Element dump:"];
  for (var k in element) {
    if (element.hasOwnProperty(k)) {
      a.push(k + ": " + element[k]);
    }
  }
  a.push("HTML: " + element.innerHTML);
  alert(a.join('\n'));
}

Whether you want the "hasOwnProperty" test or not, I don't know.

Pointy
  • 405,095
  • 59
  • 585
  • 614