JQuery wrapAll doesn't behave as expected

I am trying to wrap a created 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));

Expected Result

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

But the actual result:

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

Items are linot wrapped. In my case, innerHtml is generated on the fly from a user-created template, and the wrapper is provided separately. How can I get the internal values?

+5
source share
3 answers

wrapAllreturns the original jQuery object, not the new one. Thus, it wrapAllreturns <li>s because the object that was called was called wrapAll.

Try the following:

$("div#target").append($(innerHtmlAsText).wrapAll(wrapper).parent());
+8
source

, wrapAll , , ( jquery).

.parent(), ul.

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

.append().

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

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

DEMO

+1
source

All Articles