简体   繁体   中英

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>

You can do:

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

DEMO

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/

您可以使用outerHTML属性

$('#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/

尝试这个:

    $('#foo').parent().html();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM