admin管理员组文章数量:1336596
I want to able to get #post content include itself. jQuery's html() method only return content that does not include itself.Trying to get parent object's html does not work in all situation because that object can have siblings.
What is solution for this ?
<div id="post">
<div>content</div>
<div>
<div></div>
I want to able to get #post content include itself. jQuery's html() method only return content that does not include itself.Trying to get parent object's html does not work in all situation because that object can have siblings.
What is solution for this ?
<div id="post">
<div>content</div>
<div>
<div></div>
Share
Improve this question
asked Jan 15, 2012 at 18:00
AnyOneAnyOne
9312 gold badges12 silver badges42 bronze badges
2
- 1 Why do you want an elements html? That's bad practice. – Raynos Commented Jan 15, 2012 at 18:10
- He just wants it, that's all we have to worry about. – Ralph Lavelle Commented May 8, 2013 at 5:55
5 Answers
Reset to default 4Description
jQuery's html()
gives you only the innerHTML right. You can do
$("#post")[0].outerHTML
to get the full html but this is not crosser browser patible.
Check out this jsFiddle Demonstration
You can use this plugin to get a cross browser patible function .outerHTML()
More Information
- jQuery - OuterHTML Plugin
- jQuery.html()
You can clone the element in question and append the clone to a new element. Then you can get the HTML of the new element:
var html = $("<div>").append($("#post").clone()).html();
you can wrap
it around a virtual div
using clone
so infect you wont disturb the DOM
.
you can try like this
$('#post').clone().wrap('<div>').parent().html();
if (!Element.prototype.hasOwnProperty("outerHTML")) {
Object.defineProperty(Element.prototype, "outerHTML", {
configurable: true,
get: function getOuterHTML() {
var html = this.innerHTML;
var tag = "<" + this.tagName;
var closeTag = "</" + this.tagName + ">";
[].forEach.call(this.attributes, function (attr) {
tag += attr.nodeName + '="' + attr.nodeValue + '"';
});
tag += ">";
return tag + html + closeTag;
}
});
}
If outerHTML is not precent the following should shim it. This means you can just do
document.getElementById("post").outerHTML;
Demo
Maybe something like this:
var elem = $("#post").clone().wrap('<div>').parent().html();
Fiddle!
本文标签: javascriptHow to get Dom object39s content include itselfStack Overflow
版权声明:本文标题:javascript - How to get Dom object's content include itself? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742410398a2469668.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论