jQuery:将所有元素包装在一个div中但不包含在另一个div中

问题描述 投票:0回答:2

我有一个关于.wrapAll()的问题。到目前为止我得到了这段代码:

<div id="firstDivContainer">
  <div class="element">stuff</div>
  <div class="accordion">stuff</div>
  <div class="accordion">stuff</div>
  <div class="accordion">stuff</div>
</div>

<div id="secondDivContainer">
  <div class="element">stuff</div>
  <div class="accordion">stuff</div>
  <div class="accordion">stuff</div>
  <div class="accordion">stuff</div>
  <div class="element">stuff</div>
</div>

我想要另外一个包装第一套手风琴的div。所以我尝试了:

if ($('#firstDivContainer').find('.accordion').length != 0) {
  $(".accordion").wrapAll("<div id='accordionBox' />");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="firstDivContainer">
  <div class="element">stuff</div>
  <div class="accordion">stuff</div>
  <div class="accordion">stuff</div>
  <div class="accordion">stuff</div>
</div>

<div id="secondDivContainer">
  <div class="element">stuff</div>
  <div class="accordion">stuff</div>
  <div class="accordion">stuff</div>
  <div class="accordion">stuff</div>
  <div class="element">stuff</div>
</div>

但是他从第二组中移除了手风琴并将它们添加到第一组。结果应该是:

<div id="firstDivContainer">
  <div class="element">stuff</div>
  <div id="accordionBox">
    <div class="accordion">stuff</div>
    <div class="accordion">stuff</div>
    <div class="accordion">stuff</div>
  </div>
</div>
<div id="secondDivContainer">
  <div class="element">stuff</div>
  <div class="accordion">stuff</div>
  <div class="accordion">stuff</div>
  <div class="accordion">stuff</div>
  <div class="element">stuff</div>
</div>

但相反,我得到了

<div id="firstDivContainer">
  <div class="element">stuff</div>
  <div id="accordionBox">
    <div class="accordion">stuff</div>
    <div class="accordion">stuff</div>
    <div class="accordion">stuff</div>
    <div class="accordion">stuff</div>
    <div class="accordion">stuff</div>
    <div class="accordion">stuff</div>
  </div>
</div>
<div id="secondDivContainer">
  <div class="element">stuff</div>
  <div class="element">stuff</div>
</div>

我想解决方案只是一个小小的改变,但我目前仍然坚持这个dratz。

javascript jquery html
2个回答
3
投票

只需缩小初始选择器,所以你只在.accordion中选择#firstDivContainers:

$("#firstDivContainer .accordion").wrapAll("<div id='accordionBox' />");

JSFiddle


1
投票
$("#firstDivContainer .accordion").wrapAll("<div id='accordionBox' />");

应该这样做。

© www.soinside.com 2019 - 2024. All rights reserved.