如何在两个相同元素之间选择所有元素

How to select all elements between two same elements?

本文关键字:元素 之间 选择 两个      更新时间:2023-09-26

在一个div容器中,我想选择并分组所有标题及其内容,直到下一个标题。这些块应该有不同的背景颜色。

这是我在我的html:中得到的

<div class="container">
    <h2></h2>
    <p></p>
    <p></p>
    <ul></ul>
    <h2></h2>
    <p></p>
    <p></p>
    <p></p>
    <h2></h2>
    <p></p>
    <p></p>
    <p></p>
</div>

我需要的是:

<div class="container">
    <div class="xy">
        <h2></h2>
        <p></p>
        <p></p>
        <ul></ul>
    </div>
    <div class="xy">
        <h2></h2>
        <p></p>
        <p></p>
        <p></p>
    </div>
    <div class="xy">
        <h2></h2>
        <p></p>
        <p></p>
        <p></p>
    </div>
</div>

我试着使用nextUntil(),但到目前为止还不起作用。

如果有任何帮助,我将不胜感激。

最佳,Robin

这就完成了任务:

$('.container h2').each(function() {    //for each h2
  $(this)
    .nextUntil('h2')                    //get siblings until next h2, or all next siblings if no more h2
    .addBack()                          //include current h2
    .wrapAll('<div class="xy"/>');      //wrap it
});
$('pre').text($('.container').html());  //show it!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <h2></h2>
    <p></p>
    <p></p>
    <ul></ul>
    <h2></h2>
    <p></p>
    <p></p>
    <p></p>
    <h2></h2>
    <p></p>
    <p></p>
    <p></p>
</div>
        
<pre></pre>