tags:

views:

36

answers:

2

jQuery - is it possible to dynamically wrap a bunch of generated <li> elements (fetched via JSON) appended to a div id with <ol>, for example?

I know of the wrap() function, but that seems to do it for each element of the li. Applying the prepend("<ol>") automatically closes the tag before the each / append() loop goes through

+1  A: 
var string = "<ol>";
$.each(json, function(i, item) {
  string += "<li>" + item + "</li>";
});
string += "</ol>";
$("#myDiv").html(string);

No?

mlathe
you have to store the values in memory this way - what if your json return is rather large.. just append to render on page directly
ina
+1  A: 

Instead of .wrap() you can use .wrapAll() here, like this:

myLICollection.wrapAll('<ol></ol>');

Since you seem to already have the collection (as best as I can tell from the question) this should be a simple change. .wrap() wraps each element in the set, where as .wrapAll() wraps the entire set at once.

Nick Craver
the problem with `.wrapAll()` is that it doesn't wrap the things contained within the classes... so if you have `<li class="wrapme"><img class="someOtherClassName"></li>` it'd just wrap the li's and not the img's..
ina
nvm! was json async error causing the oddness. wrapAll works :)
ina