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
  • 14,989
  • 13
  • 101
  • 119
Abid
  • 6,969
  • 8
  • 42
  • 50

5 Answers5

11

You can do:

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

DEMO

More Info:

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

Sarfraz
  • 367,681
  • 72
  • 526
  • 573
  • 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,321
  • 3
  • 43
  • 57
3

You can use the outerHTML property:

$('#foo')[0].outerHTML
Rich O'Kelly
  • 40,274
  • 9
  • 81
  • 111
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
  • 90,891
  • 40
  • 158
  • 247
0

Try this:

    $('#foo').parent().html();
Wouter Dorgelo
  • 11,372
  • 11
  • 59
  • 79
Furqan Hameedi
  • 4,322
  • 3
  • 25
  • 34