将jQuery对象打印为HTML

将jQuery对象打印为HTML,jquery,Jquery,有没有一种将jQuery对象打印为纯HTML的好方法 例: var-img=$('img').eq(0); log(img.toString()); toString()不是这样工作的。我需要HTML等效字符串,即: 您可以将其包装,然后使用html: var img = $('img').eq(0); console.log(img.wrap("<span></span>").parent().html()); var-img=$('img').eq(0); lo

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

例:


var-img=$('img').eq(0);
log(img.toString());
toString()
不是这样工作的。我需要HTML等效字符串,即:


您可以将其包装,然后使用html:

var img = $('img').eq(0);
console.log(img.wrap("<span></span>").parent().html());
var-img=$('img').eq(0);
log(img.wrap(“”.parent().html());

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

更新

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

$.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]));

}
$('img')[0]。outerHTML


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

所以,我真的需要一个扩展吗?它与Magnar的示例相同,只是在解析之前进行克隆。如果是相同的事情,但您需要克隆他以继续移动DOM中的元素,并将其删除。它不会修改DOM吗?我们应该先克隆
img
吗?或者,如果您知道DOM中需要HTML的特定元素$('#some.selector')[0]。outerHTML只需确保将其包装在if($('#some.selector').length)中即可
$.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]));

}