6

I have this HTML:

    <ul>
        <div>
            <li>a</li>
            <li>b</li>
            <li class="break">c</li>
            <li>d</li>
            <li>f</li>
        </div>
    </ul>

What I want is where class="break" I want the parent div closed and a new one opened so I end up with this:

    <ul>
        <div>
            <li>a</li>
            <li>b</li>
        </div>
        <div>
            <li>c</li>
            <li>d</li>
            <li>f</li>
        </div>
    </ul>

Now I've tried this:

$(".break").before("</div><div>");

but jQuery doesn't act as I'd expect and instead rewrites what I have entered and puts an empty div instead. Like so:

    <ul>
        <div>
            <li>a</li>
            <li>b</li>
            <div></div>
            <li class="break">c</li>
            <li>d</li>
            <li>f</li>
        </div>
    </ul>

So how can I achieve what I am after?

Scott
  • 3,967
  • 9
  • 38
  • 56
  • 2
    I don't think `
    ` in `
      ` is a valid html
    – Andreas Wong Mar 27 '12 at 09:26
  • What @andreas said is true, div in ul is not valid. Instead of doing this, what is the final goal you want to reach. Dividing li's in columns? – Tim Mar 27 '12 at 09:28
  • The purpose would be to split them into columns. Problem is the menu I've shown is a very simplified menu and the real menu contains many layers. – Scott Mar 27 '12 at 09:30
  • If not doable with `div` I'd be happy to accept closing the `` then reopening `
      `
    – Scott Mar 27 '12 at 09:34

2 Answers2

11

Assuming you have the following markup:

<ul>
    <li>a</li>
    <li>b</li>
    <li class="break">c</li>
    <li>d</li>
    <li>f</li>
</ul>

And you want to transform it into:

<ul>
    <li>a</li>
    <li>b</li>
</ul>
<ul>
    <li class="break">c</li>
    <li>d</li>
    <li>f</li>
</ul>

You can use nextAll() with andSelf() to get the elements you want to move, then create a new <ul> and use append() to relocate the elements:

var boundary = $("li.break");
$("<ul>").insertAfter(boundary.parent()).append(boundary.nextAll().andSelf());

You can see the results in this fiddle.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
0

Excellent Solution

Ok in my case .. lets say i had multiple li.break

so following solution helped me

 $("li.break").each(function(){
     var boundary = $(this);
     $("<ul>").insertAfter(boundary.parent()).append(boundary.nextAll().andSelf());
 });    

check this fiddle http://jsfiddle.net/stLW4/127/ for more understanding

  • Hello sid its amazing but how i can achieve the that li.break is wrap in ul tag and other will work same like you made in js fiddle so it will be actually 3 ul one for a and b other for c and then for d e can i achieve this ? – Hassan Aug 30 '17 at 21:16