jQuery,获取整个元素的 html

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3614212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:44:58  来源:igfitidea点击:

jQuery, get html of a whole element

jqueryhtml

提问by Keyo

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:

我希望获得所选元素的整个 html,而不仅仅是它的内容。.html() 根据文档使用 javascripts innerHTML() 方法。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:

使用$('#divs:first').html();将只返回段落元素。我想获取整个元素的 html,如下所示:

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

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

我不能使用 .parent 因为这将返回两个子 div 的 html。

回答by Nick Craver

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:

或者使它成为一个插件,大多数人倾向于称其为“outerHTML”,如下所示:

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

Then you can just call:

然后你可以打电话:

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

回答by Pasi Jokinen

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

在典型用例中,差异可能没有意义,但使用标准 DOM 功能

$("#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 : '';  
};

回答by Shakti Shakya

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

您只需使用一行代码即可实现这一目标:

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

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

As simple as that.

就如此容易。

回答by Airy

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

您可以使用 Jquery 的 Clone() 方法轻松获取孩子本身及其所有死者(孩子),只需

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>