Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery wrapAll not behaving as expected

Tags:

jquery

I am trying to wrap a generated series of elements that are created on the fly with another element, for example:

var innerHtmlAsText = "<li>test1</li><li>test2</li>";
var wrapper = "<ul />";

$("div#target").append($(innerHtmlAsText).wrapAll(wrapper));

My expected result is

<ul>
    <li>test1</li>
    <li>test2</li>
</ul>

But the actual result is:

<li>test1</li>
<li>test2</li>

The li elements are not wrapped. In my instance the innerHtml is generated on the fly from a user generated template and the wrapper is supplied separately. How can I get the inner values wrapped?

like image 557
ilivewithian Avatar asked Jun 27 '12 14:06

ilivewithian


3 Answers

wrapAll returns the original jQuery object, not the new one. So, wrapAll is returning the <li>s, because that's the object that wrapAll was called on.

Try this:

$("div#target").append($(innerHtmlAsText).wrapAll(wrapper).parent());
like image 197
Rocket Hazmat Avatar answered Oct 24 '22 06:10

Rocket Hazmat


That happens because wrapAll does not return the wrapper, but the original object it was applied to (as most jquery functions).

Use the .parent() to get to the ul element..

$("div#target").append( $(innerHtmlAsText).wrapAll(wrapper).parent() );
like image 3
Gabriele Petrioli Avatar answered Oct 24 '22 05:10

Gabriele Petrioli


It is also possible only with .append().

var innerHtmlAsText = "<li>test1</li><li>test2</li>";
var wrapper = "<ul/>";

$("div#target").append($(wrapper).append(innerHtmlAsText));

DEMO

like image 2
thecodeparadox Avatar answered Oct 24 '22 06:10

thecodeparadox