【问题标题】:jquery :not(:first-child) wrapAll() each divjquery :not(:first-child) wrapAll() 每个 div
【发布时间】:2015-09-27 14:57:23
【问题描述】:

我想选择具有该类的 div 中除第一个元素之外的所有元素。

当前 HTML:

<div class="cpt-cv-content-item">
    <a>...</a>
    <h4>...</h4>
    ...
</div>
<div class="cpt-cv-content-item">
    <a>...</a>
    <h4>...</h4>
    ...
</div>

我尝试使用 wrap all:

$(".pt-cv-content-item :not(:first-child)").wrapAll( "<div class='new'></div>" );

此函数正确选择除第一个元素之外的所有元素,但将它们全部移动到第一个 div 中。

我想变成这样:

<div class="cpt-cv-content-item">
    <a>...</a>
    <div class='new'>
    <h4>...</h4>
    ...
    </div>
</div>
<div class="cpt-cv-content-item">
    <a>...</a>
    <div class='new'>
    <h4>...</h4>
    ...
    </div>
</div>

很遗憾,我无法编辑 html。 提前谢谢你

【问题讨论】:

    标签: jquery wrapall


    【解决方案1】:

    使用wrap 而不是wrapAll

     $(".pt-cv-content-item :not(:first-child)").wrap( "<div class='new'></div>" );
    

    wrap

    描述:在匹配元素集中的每个元素周围包裹一个 HTML 结构。

    wrapall

    描述:在匹配元素集中的所有元素周围包裹一个 HTML 结构。

    【讨论】:

    • Wrap 函数将每个被选中的元素都包裹起来,谢谢
    【解决方案2】:

    包装整个内容,然后将第一个子元素移出.new 到主div。

    使用 wrapInner() 包裹所有的孩子。使用 prependTo() 将元素移动到元素的开头。

    $(".cpt-cv-content-item").wrapInner($("<div class='new'>"));
    $('div.new').each(function(){
      $(this).children().first().prependTo($(this).closest(".cpt-cv-content-item"));
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <div class="cpt-cv-content-item">
        <a>...</a>
        <h4>...</h4>
        ...
    </div>
    <div class="cpt-cv-content-item">
        <a>...</a>
        <h4>...</h4>
        ...
    </div>

    【讨论】:

      【解决方案3】:

      我选择了 '.pt-cv-content-item' 中的所有元素:

      $(".pt-cv-content-item ").wrapInner( "<div class='new'></div>" );
      

      我移出了 '.pt-cv-content-item' div 中的第一个 a href

      $(".new a:first-child").each(function() {
          $(this).parent().before(this);
      });
      

      谢谢大家

      【讨论】:

        猜你喜欢
        • 2012-08-07
        • 1970-01-01
        • 1970-01-01
        • 2014-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-12
        相关资源
        最近更新 更多