最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to print entire HTML element in JavaScript? - Stack Overflow

programmeradmin2浏览0评论

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!

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!

Share Improve this question edited Apr 13, 2010 at 15:50 Anthony Forloney 91.8k14 gold badges118 silver badges116 bronze badges asked Apr 13, 2010 at 15:49 celicnicelicni 5203 gold badges8 silver badges16 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 7

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

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.

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');
}

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);

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.

发布评论

评论列表(0)

  1. 暂无评论