I want to get the html including the selector that I am using to get the html
let's say I have
<div id="foo">
<div id="bar">content</div>
</div>
when I do $('#foo').html()
I get
<div id="bar">content</div>
Is there a way in jquery to get the whole html including the parent(selector div)
I want this whole html
<div id="foo">
<div id="bar">content</div>
</div>
You can do:
$('#foo')[0].outerHTML;
More Info:
https://developer.mozilla.org/en/DOM/element.outerHTML
You can also do this with .clone()
and .wrap()
like
$('#foo').clone().wrap("<div/>").parent().html();
Demo: http://jsfiddle.net/joycse06/Vy5JW/
Note outerHTML
is not supported in firefox < 11.0
You can check that in Browser Compatibility section here https://developer.mozilla.org/en/DOM/element.outerHTML
So for a failsafe you can use something like following Which takes advantage of outerHTML
if available and work across browsers
$foo = $('#foo');
var outerHtml = ('outerHTML' in $foo[0])? $foo[0].outerHTML
: $foo.clone().wrap("<div/>").parent().html();
Updated Demo http://jsfiddle.net/joycse06/Vy5JW/1/
You can use the outerHTML
property:
$('#foo')[0].outerHTML
In addition to Sarfraz's answer, if you're using jQuery, you can pack it into its own plugin:
(function($) {
$.fn.outer = function() {
return $(this)[0].outerHTML;
};
})(jQuery);
Here is a demo: http://jsfiddle.net/WkH4z/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With