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!