views:

242

answers:

2

For example if I have HTML ul list like

<ul id="ulIdentificator"> 
    <li id="li0"></li>
    <li id="li1"></li>
    <li id="li2"><label id="label1"></label></li>   
</ul>

If I use jQuery like this

var htmlStr = $("#li2").html();

The result will be only string that contains label tag <LABEL id="label1"></LABEL></li> I need to get Html string that contains this <LI id="li2"><LABEL id="label1"></LABEL></LI>

A: 

jQuery OuterHTML , OuterHTML II

andres descalzo
The OuterHTML II technique is so simple, it's worth reproducing in the body of your answer.
Jeff Sternal
Ok, this is the right answer, but I will accept it if you add some examples not just 2 links, for other SO folks to see it here.
nemke
+2  A: 

The second OuterHTML technique Andres mentions (from the Web Architects' Blog) works on all browsers, so it's probably a better choice. The basic idea is that you can get an element's outer HTML by making it another element's innerHTML:

var outerHtml = $("<div/>").append($("#li2").clone()).html();

There's only one slightly tricky bit - make sure to clone your original element, so you don't remove it from the DOM.

If you do this often or want to do this to arrays of elements, it's probably worth following the linked example and make a little plugin to do this.

Jeff Sternal