Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...