Combining multiple ULs into one UL

How to combine several ul into one ul ?

For example, how can I combine the following.

 <ul> <li>one</li> <li>two</li> </ul> <ul> <li>three</li> </ul> <ul> <li>four</li> </ul> <ul> <li>five</li> </ul> 

Something like that

 <ul> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> </ul> 

+4
source share
3 answers

The great thing about .append() and .appendTo() is that they will move existing DOM elements, not copy them, as you might expect:

 $('ul').children('li').appendTo('ul:first'); // move all LIs to the first UL $('ul').not(':first').remove(); // delete the extra ULs 

Set the 'ul' selector as needed; I recommend using a generic class instead of a generic tag switcher.

http://jsfiddle.net/j76Lu/

Slightly optimized (thanks, adeneo ):

 $('ul').not(':first').remove().children('li').appendTo('ul:first'); 

http://jsfiddle.net/j76Lu/1/

or even better:

 $('ul:gt(0)').remove().children('li').appendTo('ul:eq(0)'); 

http://jsfiddle.net/j76Lu/2/

+16
source
 $('<ul />').append($('ul').remove().children('li')).appendTo('body'); 

Fiddle

+1
source
 var newUl = $('<ul>'); $('ul').each(function() { $(this).find('li').each(function() { newUl.append($(this)) }); $(this).remove(); }); $('selector').append(newUl); 
0
source

All Articles