jQuery, get html of a whole element [duplicate]

I wish to get the entire html of a selected element not just it's contents. .html() uses javascripts innerHTML() method according to the documentation. HTML:

<div id="divs">
  <div id="div1">
    <p>Some Content</p>
  </div>
  <div id="div2">
    <p>Some Content</p>
  </div>
</div>

Using $('#divs:first').html(); will return just the paragraph element. I want to get the html for the whole element, like so:

  <div id="div1">
    <p>Some Content</p>
  </div>

I can't use .parent because this will return html of both child divs.


Solution 1:

You can clone it to get the entire contents, like this:

var html = $("<div />").append($("#div1").clone()).html();

Or make it a plugin, most tend to call this "outerHTML", like this:

jQuery.fn.outerHTML = function() {
  return jQuery('<div />').append(this.eq(0).clone()).html();
};

Then you can just call:

var html = $("#div1").outerHTML();

Solution 2:

Differences might not be meaningful in a typical use case, but using the standard DOM functionality

$("#el")[0].outerHTML

is about twice as fast as

$("<div />").append($("#el").clone()).html();

so I would go with:

/* 
 * Return outerHTML for the first element in a jQuery object,
 * or an empty string if the jQuery object is empty;  
 */
jQuery.fn.outerHTML = function() {
   return (this[0]) ? this[0].outerHTML : '';  
};