[jquery] jQuery, get html of a whole element

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.

This question is related to jquery html

The answer is


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();

You can achieve that with just one line code that simplify that:

$('#divs').get(0).outerHTML;

As simple as that.


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 : '';  
};

You can easily get child itself and all of its decedents (children) with Jquery's Clone() method, just

var child = $('#div div:nth-child(1)').clone();  

var child2 = $('#div div:nth-child(2)').clone();

You will get this for first query as asked in question

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