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

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

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

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

我的初始加价:

$('.main .hdr').parents('p').each(function() {
  $(this).nextUntil($(this)).addBack().wrapAll('<div class="wrapper" />');
});
<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>

电流输出:

<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>

期望的输出:

<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>

JSFiddle

javascript jquery html string parent
1个回答
2
投票

像这样的东西,将选择传递给nextUntil,甚至只是p:has(.hdr)会起作用,而不是$(this)

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

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

FIDDLE

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