jQuery, get html of a whole element

JqueryHtml

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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 - Jquery

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

Solution 3 - Jquery

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

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

As simple as that.

Solution 4 - Jquery

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKeyoView Question on Stackoverflow
Solution 1 - JqueryNick CraverView Answer on Stackoverflow
Solution 2 - JqueryPasi JokinenView Answer on Stackoverflow
Solution 3 - JqueryShakti ShakyaView Answer on Stackoverflow
Solution 4 - JqueryAiryView Answer on Stackoverflow