Output jQuery object as HTML

Is there a good way to print a jQuery object as pure HTML?

Example:

<img src="example.jpg">

<script>
var img = $('img').eq(0);
console.log(img.toString());
</script>

      

toString()

does not work. I want an equivalent HTML string, i.e.

<img src="example.jpg">

+22


source to share


3 answers


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

Update



Update link and include 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]));

}

      

+6


source


$('img')[0].outerHTML



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

+22


source


You can wrap it up and then use html:

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

      

+15


source







All Articles