javascript – 包装两个元素之间的所有元素

前端之家收集整理的这篇文章主要介绍了javascript – 包装两个元素之间的所有元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下 HTML
<div class="bar-something"><div class="fn-label"> SOMETHING</div> </div>
<div class="bar-appointment"><div class="fn-label"> Ap1</div></div>
<div class="bar-appointment"><div class="fn-label"> Ap2</div></div>
<div class="bar-appointment"><div class="fn-label"> Ap3</div></div>
<div class="bar-something-else"><div class="fn-label"> SOMETHING</div></div>
<div class="bar-appointment"><div class="fn-label"> Ap1</div></div>
<div class="bar-appointment"><div class="fn-label"> Ap2</div></div>
<div class="bar-appointment"><div class="fn-label"> Ap3</div></div>
<div class="bar-something-odd"><div class="fn-label"> SOMETHING</div></div>

我想用另一个DIV包装所有bar-appointment元素,所以DOM看起来像:

<div class="bar-something"><div class="fn-label"> SOMETHING</div> </div>
<div class="test">
  <div class="bar-appointment"><div class="fn-label"> Ap1</div></div>
  <div class="bar-appointment"><div class="fn-label"> Ap2</div></div>
<div>
<div class="bar-something-else"><div class="fn-label"> SOMETHING</div></div>
<div class="test">
    <div class="bar-appointment"><div class="fn-label"> Ap1</div></div>
    <div class="bar-appointment"><div class="fn-label"> Ap2</div></div>
    <div class="bar-appointment"><div class="fn-label"> Ap3</div></div>
    <div class="bar-appointment"><div class="fn-label"> Ap4</div></div>
    <div class="bar-appointment"><div class="fn-label"> Ap5</div></div>
</div>
<div class="bar-something-odd"><div class="fn-label"> SOMETHING</div></div>

我已经尝试过以下内容,但所有内部标签也被包裹起来,我不希望这样.

$('.bar-appointment').each(function() {
  $(this).nextUntil("div[class!='bar-appointment']").andSelf().wrapAll('<div class="test"></div>')});

我也试过只使用wrap,这只是单独包装每个元素,而不是我想要的组.

这样做的最好方法是什么?

解决方法

首先,您可以通过删除以前兄弟作为条形约会的条形约会元素来找到所有第一个条形约会元素(集合).然后迭代它并找到所有兄弟作为条形约会元素并包装所有它们
$('.bar-appointment').not('.bar-appointment + .bar-appointment').each(function() {
  $(this).nextUntil(":not(.bar-appointment)").addBack().wrapAll('<div class="test"> </div>')
})
.test {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="bar-something"><div class="fn-label"> SOMETHING</div> </div>
<div class="bar-appointment"><div class="fn-label"> Ap1</div></div>
<div class="bar-appointment"><div class="fn-label"> Ap2</div></div>
<div class="bar-appointment"><div class="fn-label"> Ap3</div></div>
<div class="bar-something-else"><div class="fn-label"> SOMETHING</div></div>
<div class="bar-appointment"><div class="fn-label"> Ap1</div></div>
<div class="bar-appointment"><div class="fn-label"> Ap2</div></div>
<div class="bar-appointment"><div class="fn-label"> Ap3</div></div>
<div class="bar-something-odd"><div class="fn-label"> SOMETHING</div></div>
原文链接:https://www.f2er.com/js/158508.html

猜你在找的JavaScript相关文章