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?
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());
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() );
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With