Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get full html instead of just innner html

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>
like image 356
Abid Avatar asked Jun 17 '12 10:06

Abid


4 Answers

You can do:

$('#foo')[0].outerHTML;

DEMO

More Info:

https://developer.mozilla.org/en/DOM/element.outerHTML

like image 102
Sarfraz Avatar answered Oct 03 '22 20:10

Sarfraz


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/

like image 35
Prasenjit Kumar Nag Avatar answered Oct 03 '22 21:10

Prasenjit Kumar Nag


You can use the outerHTML property:

$('#foo')[0].outerHTML
like image 36
Rich O'Kelly Avatar answered Oct 03 '22 22:10

Rich O'Kelly


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/

like image 27
David G Avatar answered Oct 03 '22 20:10

David G