jQuery add closing tag and then reopen when using .before()

时光总嘲笑我的痴心妄想 提交于 2019-12-18 06:57:14

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/9886676/jquery-add-closing-tag-and-then-reopen-when-using-before

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!