3

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>

Matthew Groves
  • 25,181
  • 9
  • 71
  • 121
nemke
  • 2,440
  • 3
  • 37
  • 57
  • 1
    Next jquery question after your was http://stackoverflow.com/questions/1917040/can-i-get-the-full-html-represenation-of-an-htmlelment-dom-object – Roatin Marth Dec 16 '09 at 20:49

3 Answers3

7

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
  • 47,787
  • 8
  • 93
  • 120
  • 1
    +1 very good answer. But in [this other question](http://stackoverflow.com/questions/995760/in-jquery-are-there-any-function-that-similar-to-html-or-text-but-return-the/5314397#5314397) you have you have the same technique with also a solution for a problem with **IFrames**. – Mariano Desanze Mar 15 '11 at 17:42
1

You can also write a small jQuery plugin with proposed method from Jeff Sternal:

// jQuery plugin 'htmlWithParent'

jQuery(function($) {

  $.fn.htmlWithParent = function() { return $j("<div/>").append($j(this).clone()).html(); };

});

and use this small cutom plugin, for example:

var htmlCode = $("<p><span>Helo world!</span></p>");

// Return only child nodes: <span>Helo world!</span>
var output1 = $(htmlCode).html();

// Return whole HTML code (childs + parent): <p><span>Helo world!</span></p>
var output2 = $(htmlCode).htmlWithParent();

Very useful method. ;)

Piotr
  • 377
  • 4
  • 11
-1

jQuery OuterHTML , OuterHTML II

miku
  • 181,842
  • 47
  • 306
  • 310
andres descalzo
  • 14,887
  • 13
  • 64
  • 115
  • 3
    The OuterHTML II technique is so simple, it's worth reproducing in the body of your answer. – Jeff Sternal Dec 16 '09 at 19:44
  • 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 Dec 16 '09 at 20:23