Mohamed Abo ElGhranek
Mohamed Abo ElGhranek

Reputation: 107

Split <ul> into two divs one for first-child and one for the rest

using jquery i would like to split ul li tags into two divs

Example

<ul>
<li>first</li>
<li>second</li>
<li>third</li>
<li>4th</li>
<li>5th</li>
<li>6th</li>
</ul>

to

  <div class="right">
    <ul>
        <li>first</li>
    </ul>
     </div>

<div class="left">
        <ul>
         <li>second</li>
         <li>third</li>
         <li>4th</li>
         <li>5th</li>
         <li>6th</li>
        </ul>
</div>

this method i will use for scrolling the left section only with fixed right one

Upvotes: 2

Views: 558

Answers (1)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Though your html is invalid (li should not be wrapped inside a div) you can try like,

var li = $('li');

li.filter(':first').wrap('<div class="right"></div>');
li.filter(':not(:first)').wrapAll('<div class="left"></div>');

DEMO

The following can make your html valid,

var li = $('li');

li.filter(':first').wrap('<div class="first"></div>').parent().wrap('<li></li>');
li.filter(':not(:first)').wrapAll('<div class="second"></div>').parent().wrap('<li></li>');

DEMO

As per your new requirement you can do like,

var li = $('li');
$('ul').remove();

var leftLi = li.filter(':first').detach();
var rightLi = li.filter(':not(:first)').detach();

leftLi.appendTo($('body')).wrap('<ul></ul>').wrap('<div></div>');
rightLi.appendTo($('body')).wrapAll('<ul></ul>').wrap('<div></div>');

Note: you should take care of the ids and classes of the ul elements, since I don't know the html structure. And have you noticed that .appendTo('body'), I just written that for a demonstration purpose, but you have to decide where the elements should be appended.

DEMO

Upvotes: 1

Related Questions