tags:

views:

1306

answers:

4

Given a jQuery result set, how do you convert that back into plain HTML?

<div class="abc">
    foo <strong>FOO</strong>
</div>
<div class="def">
    bar
</div>

--

var $mySet = $('div');

Given $mySet, how would you go about returning to the plain HTML above?

A: 
var $mySet = $('div');
var html = $mySet.html();

If you want the element's HTML as well (untested):

var $mySet = $('div');
var html = $mySet.clone().wrap('<div></div>').html();

By the way, here $ is part of the variable name. Javascript doesn't require a $ like in PHP for variable names, but it doesn't hurt to have it.

strager
that's incorrect sorry. this will just return the inner HTML of the first div. i'm actually looking to get it to return to HTML like in the first example above.
nickf
Give my second snippet a try.
strager
A: 

Using the jQuery appendTo method, if I understand well what you mean by "returning to the plain HTML above".

gizmo
+2  A: 

i'd suggest creating a temporary container, then grabbing the html() of that new container:

var html = $('<div>').append( $('div').clone() ).html();
alert(html);

// alerts:

<div class="abc">
    foo <strong>FOO</strong>
</div><div class="def">
    bar
</div>
Owen
A: 

maybe what you want is a client-side templating engine. check out the post Client Templating with jQuery

i'm using it and it's pretty cool. You just set the template you want to use inside a div, then you feed it with a json object/array and that's it.

vitorsilva