Chris Armstrong
Chris Armstrong

Reputation: 3625

How to wrap an <ul> in another <ul>?

I have an unordered list that I would like to wrap inside another unordered list in jQuery, using the following code:

$('ul.innerlist').prepend('<ul><li>');
$('ul.innerlist').append('</li></ul>');

However, rather than the first line creating the opening tags and the second creating closing tags (and wrapping the .innerlist), the first line appears to create both open and close tags, resulting in this

<ul>
  <li></li>
</ul>
<ul class="innerlist">
  <li></li>
</ul>

Instead of this:

<ul>
  <li>
    <ul class="innerlist">
      <li></li>
    </ul>
  </li>
</ul>

Upvotes: 1

Views: 1075

Answers (3)

Brad Christie
Brad Christie

Reputation: 101604

try the following:

$('ul.innerlist').each(function(i,v){v=$('<ul><li></li></ul>').append(v);});

or the wrap function.

Upvotes: 0

btiernay
btiernay

Reputation: 8129

See http://api.jquery.com/wrap/

Upvotes: 2

user113716
user113716

Reputation: 322492

This uses jQuery's wrap() method to wrap the selected elements with the elements you provide.

Example: http://jsfiddle.net/patrick_dw/bD8LQ/

$('ul.innerlist').wrap('<ul><li></li></ul>');

Upvotes: 4

Related Questions