6

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>
akjoshi
  • 15,374
  • 13
  • 103
  • 121
Abid
  • 7,149
  • 9
  • 44
  • 51

5 Answers5

11

You can do:

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

DEMO

More Info:

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

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • The second option would return the html of any siblings of `#foo` also. – Rich O'Kelly Jun 17 '12 at 10:44
  • 1
    Warning: This doesn't work in Firefox 10, which was released half a year ago. Which in most definitions would exclude users with an updated browser. So for a stable user experience, see Joy's answer below or any in this question: http://stackoverflow.com/questions/1700870/how-do-i-do-outerhtml-in-firefox – Simeon Jun 17 '12 at 11:18
4

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/

Prasenjit Kumar Nag
  • 13,391
  • 3
  • 45
  • 57
3

You can use the outerHTML property:

$('#foo')[0].outerHTML
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
1

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/

David G
  • 94,763
  • 41
  • 167
  • 253
0

Try this:

    $('#foo').parent().html();
Wouter Dorgelo
  • 11,770
  • 11
  • 62
  • 80
Furqan Hameedi
  • 4,372
  • 3
  • 27
  • 34