views:

101

answers:

6

given this html:

<li id="the_list_item"><img src="some_img"></li>

and this selectior:

$("#the_list_item")

I want to get the full html from the object return by the jQuery selector.

Using:

$("#the_list_item").html()

...just gives me the inner html (the <img src="some_img"> part)

But since:

$("#the_list_item").attr("id")

gives me 'the_list_item', this indicated that the whole list item is indeed included in the object returned.. so how do I get the full code from that object?

I want to get a String: <li id="the_list_item"><img src="some_img"></li> from my object, but can't find the way to do it.

+2  A: 

Have you tried $("#the_list_item").parent().html()?

akellehe
Works only if the parent has only this element and nothing else.
Chetan Sastry
+2  A: 

I'm not sure if this works, but it might be worth a shot:

var html = $('#the_list_item')[0].outerHTML;
alert(html);
Tatu Ulmanen
this is elegant.. will it work in all browsers? it does work in Safari.I found out that dumping the object (in my case a jQuery ui.draggable) to the Safari Dev console: console.log(ui.draggable);revealed the total skeleton of this jQuery object, and it looks like an array (though it is an object) and it has something like another object at index 0, which has a outerHTML property that holds the entire html string.. so yes, using $('#the_list_item')[0].outerHTML or in my case ui.draggable[0].outerHTML rturns exactly what i'm looking for.
mikkelbreum
+1  A: 

There's no "outer html" equivalent in jQuery, but this might help: http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html

codersarepeople
A: 

There are plugins for that. Just google for "jQuery outerhtml". The idea behind most of them is to clone the element, append it to an empty div and get that div's html.

Chetan Sastry
+1  A: 

Here you can find a nice solution in the form of the code for a jQuery outerHtml plugin: http://yelotofu.com/2008/08/jquery-outerhtml/

Dave
+4  A: 

One way is to create your own wrapper:

$("#the_list_item").wrap('<div>').parent().html();

...do your thing, then unwrap:

$("#the_list_item").unwrap();
Ken Redler