我试图用jQuery获取所选对象的HTML。我知道.html()函数;问题是我需要包含所选对象的HTML(在本例中为表行,其中.HTML()仅返回行内的单元格)。
我四处搜索,发现了一些非常“黑客”类型的方法来克隆对象,将其添加到新创建的div等,但这似乎真的很肮脏。有没有更好的方法,或者jQuery(1.4.2)的新版本是否提供任何类型的outerHtml功能?
我试图用jQuery获取所选对象的HTML。我知道.html()函数;问题是我需要包含所选对象的HTML(在本例中为表行,其中.HTML()仅返回行内的单元格)。
我四处搜索,发现了一些非常“黑客”类型的方法来克隆对象,将其添加到新创建的div等,但这似乎真的很肮脏。有没有更好的方法,或者jQuery(1.4.2)的新版本是否提供任何类型的outerHtml功能?
当前回答
我相信目前(2012年5月1日),所有主流浏览器都支持outerHTML功能。在我看来,这段话就足够了。我个人会选择记住这一点:
// Gives you the DOM element without the outside wrapper you want
$('.classSelector').html()
// Gives you the outside wrapper as well only for the first element
$('.classSelector')[0].outerHTML
// Gives you the outer HTML for all the selected elements
var html = '';
$('.classSelector').each(function () {
html += this.outerHTML;
});
//Or if you need a one liner for the previous code
$('.classSelector').get().map(function(v){return v.outerHTML}).join('');
编辑:element.outerHTML的基本支持统计信息
火狐(壁虎):11。。。。发布日期:2012-03-13铬:0.2…………发布2008-09-02Internet Explorer 4.0…1997年发布歌剧7。。。。。。。。。。。。。。。。。。。。。。发布日期:2003-01-28Safari 1.3…………..2006-01-12发布
其他回答
我相信目前(2012年5月1日),所有主流浏览器都支持outerHTML功能。在我看来,这段话就足够了。我个人会选择记住这一点:
// Gives you the DOM element without the outside wrapper you want
$('.classSelector').html()
// Gives you the outside wrapper as well only for the first element
$('.classSelector')[0].outerHTML
// Gives you the outer HTML for all the selected elements
var html = '';
$('.classSelector').each(function () {
html += this.outerHTML;
});
//Or if you need a one liner for the previous code
$('.classSelector').get().map(function(v){return v.outerHTML}).join('');
编辑:element.outerHTML的基本支持统计信息
火狐(壁虎):11。。。。发布日期:2012-03-13铬:0.2…………发布2008-09-02Internet Explorer 4.0…1997年发布歌剧7。。。。。。。。。。。。。。。。。。。。。。发布日期:2003-01-28Safari 1.3…………..2006-01-12发布
$("#myTable").parent().html();
也许我没有正确理解您的问题,但这将获得所选元素的父元素的html。
这就是你想要的吗?
2014年编辑:问题和此回复来自2010年。当时,还没有更好的解决方案。现在,许多其他回复都更好:比如埃里克·胡(Eric Hu)的回复,或者雷·卡查(Re Capcha)的回复。
本网站似乎为您提供了一个解决方案:jQuery:outerHTML|Yelotofu
jQuery.fn.outerHTML = function(s) {
return s
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
};
你可以在这里找到一个很好的.outerHTML()选项https://github.com/darlesson/jquery-outerhtml.
与仅返回元素的html内容的.html()不同,此版本的.outerHTML()返回所选元素及其html内容,或将其替换为.replaceWith()方法,但不同之处在于,替换的html可以通过链接继承。
示例也可以在上面的URL中看到。
你也可以这样做
document.getElementById(id).outerHTML
其中id是要查找的元素的id