选择并使用兄弟元素包装特定的父元素,直到下一个特定的父元素

时间:2015-04-14 17:05:16

标签: javascript jquery html string parent

我希望使用jQuery来选择p标签,这些标签是具有某个类hdr的范围的祖父元素,然后我想要包装该标签及其所有标签#39 ;兄弟姐妹直到下一个p标签,它是hdr类的父母,依此类推。

我遇到的问题是第二个和第三个包装器以及包含内容的内容最终会嵌套在前一个包装器中,而不是一个接一个地打印每个包装器。

我的初始加价:



$('.main .hdr').parents('p').each(function() {
  $(this).nextUntil($(this)).addBack().wrapAll('<div class="wrapper" />');
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">

  <p><strong><span class="hdr">Heading #1</span></strong></p>
  <p>Some paragraph text</p>
  <p>Some paragraph text</p>
  <p>Some paragraph text</p>
  <p>Some paragraph text</p>

  <p><strong><span class="hdr">Heading #2</span></strong></p>
  <p>Some paragraph text</p>
  <p>Some paragraph text</p>

  <p><strong><span class="hdr">Heading #3</span></strong></p>
  <p>Some paragraph text</p>
  <p>Some paragraph text</p>
  <p>Some paragraph text</p>
  <p>Some paragraph text</p>
  <p>Some paragraph text</p>

</div>
&#13;
&#13;
&#13;

当前输出:

&#13;
&#13;
<div class="main">

  <div class="wrapper">
    <p><strong><span class="hdr">Heading #1</span></strong></p>
    <p>Some paragraph text</p>
    <p>Some paragraph text</p>
    <p>Some paragraph text</p>
    <p>Some paragraph text</p>
    <div class="wrapper">
      <p><strong><span class="hdr">Heading #2</span></strong></p>
      <p>Some paragraph text</p>
      <p>Some paragraph text</p>
      <div class="wrapper">
        <p><strong><span class="hdr">Heading #3</span></strong></p>
        <p>Some paragraph text</p>
        <p>Some paragraph text</p>
        <p>Some paragraph text</p>
        <p>Some paragraph text</p>
        <p>Some paragraph text</p>
      </div>
    </div>
  </div>

</div>
&#13;
&#13;
&#13;

期望的输出:

&#13;
&#13;
<div class="main">

  <div class="wrapper">
    <p><strong><span class="hdr">Heading #1</span></strong></p>
    <p>Some paragraph text</p>
    <p>Some paragraph text</p>
    <p>Some paragraph text</p>
    <p>Some paragraph text</p>
  </div>

  <div class="wrapper">
    <p><strong><span class="hdr">Heading #2</span></strong></p>
    <p>Some paragraph text</p>
    <p>Some paragraph text</p>
  </div>

  <div class="wrapper">
    <p><strong><span class="hdr">Heading #3</span></strong></p>
    <p>Some paragraph text</p>
    <p>Some paragraph text</p>
    <p>Some paragraph text</p>
    <p>Some paragraph text</p>
    <p>Some paragraph text</p>
  </div>

</div>
&#13;
&#13;
&#13;

JSFiddle

1 个答案:

答案 0 :(得分:2)

这样的事情,将选择内容传递给nextUntil,甚至只传递p:has(.hdr),而不是$(this)

var elems = $('.main p:has(.hdr)');

elems.each(function() {
    $(this).nextUntil(elems).addBack().wrapAll('<div class="wrapper" />');
});

FIDDLE