开发者

Print out jQuery object as HTML

开发者 https://www.devze.com 2022-12-13 21:03 出处:网络
Is there a good way of printing out a jQuery object as pure HTML? ex: <img src=\"example.jpg\"> <script>

Is there a good way of printing out a jQuery object as pure HTML?

ex:

<img src="example.jpg">

<script>
var i开发者_如何转开发mg = $('img').eq(0);
console.log(img.toString());
</script>

toString() doesn't work this way. I need the HTML equivalent string , i.e:

<img src="example.jpg">


$('img')[0].outerHTML

will give you the HTML of the first img on the page. You will then need to use a for loop to get the HTML of all the images, or put an ID on the image and specify it only in the jQuery selector.


You could wrap it and then use html:

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


If you need to print the object in HTML format, use this extension outerHTML or this outerHTML.

Update

Update the link and include the code for second link:

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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消