将jQuery对象打印为HTML

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

例如:

  var img = $('img').eq(0); console.log(img.toString());  

toString()不能以这种方式工作。 我需要HTML等效字符串,即:

如果您需要以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])); } 

$('img')[0].outerHTML

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

你可以包装然后使用html:

 var img = $('img').eq(0); console.log(img.wrap("").parent().html());