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

时间:2014-11-10 17:59:04

标签: javascript jquery html

我对.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>
&#13;
&#13;
&#13;

我希望另一个div包装第一组手风琴。所以我尝试了:

&#13;
&#13;
if ($('#firstDivContainer').find('.accordion').length != 0) {
  $(".accordion").wrapAll("<div id='accordionBox' />");
}
&#13;
<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>
&#13;
&#13;
&#13;

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

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

但我得到了

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

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

2 个答案:

答案 0 :(得分:3)

只需缩小初始选择器,因此您只在.accordion内选择#firstDivContainer

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

JSFiddle

答案 1 :(得分:1)

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

应该这样做。