Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining multiple ULs into one UL

Tags:

jquery

How can I combine multiple uls 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>

To something like this

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

like image 275
breezy Avatar asked Dec 03 '22 01:12

breezy


2 Answers

The great thing about .append() and .appendTo() is that they will move existing DOM elements instead of copying 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

Customize the 'ul' selector as needed; I recommend using a common class instead of a general tag selector.

http://jsfiddle.net/j76Lu/

Slightly more 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/

like image 83
Blazemonger Avatar answered Jan 02 '23 17:01

Blazemonger


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

FIDDLE

like image 28
adeneo Avatar answered Jan 02 '23 17:01

adeneo