Get full html instead of just innner html

I want to get html, including the selector that I use to get html

let's say that 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 any way in jquery to get all html including parent (div selector)

I need all the html

 <div id="foo"> <div id="bar">content</div> </div> 
+6
source share
5 answers

You can do:

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

Demo

Additional Information:

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

+11
source

You can also do this with .clone() and .wrap() as

 $('#foo').clone().wrap("<div/>").parent().html(); 

Demo: http://jsfiddle.net/joycse06/Vy5JW/

Note outerHTML not supported in firefox < 11.0 You can check that in the browser compatibility section here https://developer.mozilla.org/en/DOM/element.outerHTML

So, for fault tolerance, you can use something like the following, which uses outerHTML if available and works in 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/

+4
source

You can use the outerHTML property :

 $('#foo')[0].outerHTML 
+3
source

In addition to Sarfraz's answer, if you use jQuery, you can pack it into your own plugin:

 (function($) { $.fn.outer = function() { return $(this)[0].outerHTML; }; })(jQuery);​ 

Here is a demo: http://jsfiddle.net/WkH4z/

+1
source

Try the following:

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

Source: https://habr.com/ru/post/918276/


All Articles