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

时间:2015-11-04 19:44:32

标签: javascript jquery html css

在div-container中我想选择所有标题及其内容,直到下一个标题为止。这些块应具有不同的背景颜色。

这是我在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()但到目前为止它对我没用。

我将不胜感激。

最佳, 罗宾

1 个答案:

答案 0 :(得分:8)

这就是诀窍:

$('.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>