选择彼此相邻的元素,并在它们周围添加包装器

时间:2019-07-12 05:55:18

标签: javascript jquery

我正在尝试选择彼此相邻的.tab元素,并在它们周围添加包装器,但还需要以某种方式转义其中仅包含<p>的{​​{1}}。

这是当前进展https://jsfiddle.net/chille1987/jLks6v3n/13/的小提琴

JS代码

<br/>

CSS代码

$(document).ready(function() {
  const wrapper = $('<div class="wrapper"></div>');

  // Select tabs next to each other and add a wrapper around them
  $(':not(.tab) + .tab, * > .tab:first-of-type').each(function() {
    $(this).nextUntil(':not(.tab)').addBack().wrapAll(wrapper);
  });

});

HTML代码

.wrapper {
  border: 1px solid blue;
  padding: 10px;
}

.tab {
  border: 1px solid #ef445a;
  padding: 10px;
  margin-bottom: 5px;
}

我正在尝试这样的标记:

<div id="fr-wrapper">

  <div class="tab">
    <h2>Title</h2>
  </div>
  <div class="tab">
    <h2>Title</h2>
  </div>
  <div class="tab">
    <h2>Title</h2>
  </div>

  <p>Some text is here.</p>

  <div class="tab">
    <h2>Title</h2>
  </div>
  <div class="tab">
    <h2>Title</h2>
  </div>

  <!-- Need to escape this somehow if <p> only contains <br/> -->
  <p><br/></p>

  <div class="tab">
    <h2>Title</h2>
  </div>
  <div class="tab">
    <h2>Title</h2>
  </div>


  <p>Some text goes here as well</p>
  <div class="tab">
    <h2>Title</h2>
  </div>
  <div class="tab">
    <h2>Title</h2>
  </div>
  <div class="tab">
    <h2>Title</h2>
  </div>

</div>

是否有一种方法可以某种方式检测到<div class="wrapper"> <div class="tab"> <h2>Title</h2> </div> <div class="tab"> <h2>Title</h2> </div> <div class="tab"> <h2>Title</h2> </div> </div> <p>Some text is here</p> <div class="wrapper"> <div class="tab"> <h2>Title</h2> </div> <div class="tab"> <h2>Title</h2> </div> <!-- Need to remove this so there is 4 .tab elements --> <p><br/></p> <div class="tab"> <h2>Title</h2> </div> <div class="tab"> <h2>Title</h2> </div> </div> <p>Some text goes here</p> <div class="wrapper"> <div class="tab"> <h2>Title</h2> </div> <div class="tab"> <h2>Title</h2> </div> <div class="tab"> <h2>Title</h2> </div> </div> 而不将其包含在包装中,但还可以将仅由<p><br/></p>分隔的.tab元素连接起来?

0 个答案:

没有答案