将jQuery对象打印为HTML

Dav*_*ing 22 jquery

有没有一种将jQuery对象打印为纯HTML的好方法?

例如:

<img src="example.jpg">

<script>
var img = $('img').eq(0);
console.log(img.toString());
</script>
Run Code Online (Sandbox Code Playgroud)

toString()不这样做.我需要HTML等效字符串,即:

<img src="example.jpg">

bma*_*i44 24

$('img')[0].outerHTML

将为您提供页面上第一个img的HTML.然后,您将需要使用for循环来获取所有图像的HTML,或者在图像上放置ID并仅在jQuery选择器中指定它.


Mag*_*nar 15

你可以包装然后使用html:

var img = $('img').eq(0);
console.log(img.wrap("<span></span>").parent().html());
Run Code Online (Sandbox Code Playgroud)

  • 它不会修改DOM吗?我们应该首先克隆`img`吗? (3认同)

and*_*lzo 6

如果您需要以HTML格式打印对象,请使用此扩展名outerHTML或此outerHTML.

更新

更新链接并包含第二个链接的代码:

$.fn.outerHTML = function(){

    // IE, Chrome & Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning
    return (!this.length) ? this : (this[0].outerHTML || (
      function(el){
          var div = document.createElement('div');
          div.appendChild(el.cloneNode(true));
          var contents = div.innerHTML;
          div = null;
          return contents;
    })(this[0]));

}
Run Code Online (Sandbox Code Playgroud)