开发者

jQuery, get html of a whole element [duplicate]

开发者 https://www.devze.com 2023-01-13 18:27 出处:网络
This question already has answers here: Get selected element's outer HTML (30 answers) Closed 5 years ago.
This question already has answers here: Get selected element's outer HTML (30 answers) Closed 5 years ago.

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>S开发者_StackOverflow中文版ome 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.


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


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 achieve that with just one line code that simplify that:

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

As simple as that.


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

精彩评论

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