简体   繁体   English

有没有办法wrapAll()但忽略一个元素?

[英]Is there a way to wrapAll() but ignore one element?

If you have the following code: 如果您具有以下代码:

<div class="parent">

    <div class="1"></div>
    <div class="2"></div>
    <div class="3"></div>
    <div class="4"></div>
    <div class="5"></div>   

</div>

How can I wrap a new div around div with class 2,3,4,5 so it looks like this: 我如何用2,3,4,5类在div周围包裹一个新的div,所以看起来像这样:

<div class="parent">

    <div class="1"></div>

    <div class="sub">
        <div class="2"></div>
        <div class="3"></div>
        <div class="4"></div>
        <div class="5"></div> 
    </div> 

</div>

wrapAll on the parent would wrap everything with a new div, is there a way to make it ignore the first div? 父对象上的wrapAll会用新的div包装所有内容,有没有办法使它忽略第一个div?

Use gt(0) to select all but the first one div(direct descendant) and wrapAll. 使用gt(0)选择除第一个div(直接后代)和wrapAll以外的所有内容。 This will select all divs with index greater than 0 present under .parent div. 这将选择.parent div下存在索引大于0的.parent div。

$('.parent > div:gt(0)').wrapAll('<div class="sub">');

Fiddle 小提琴

See :gt() :gt()

Output: 输出:

<div class="parent">

    <div class="1">1</div>
    <div class="sub">
            <div class="2">2</div>
            <div class="3">3</div>
            <div class="4">4</div>
            <div class="5">5</div>
    </div>
</div>

Use the not() filter or the :not() selector . 使用not()过滤器:not()选择器

$('.parent div').not('.1').wrapAll('<div class="sub">');

Or alternatively: 或者:

$('.parent div:not(.1)').wrapAll('<div class="sub">');

You can also use div:first-child in place of .1 if you always want to ignore the first element. 如果您始终想忽略第一个元素,也可以使用div:first-child代替.1

If the element you want to keep out is not necessarily the first, you could use: 如果要保留的元素不一定是第一个元素,则可以使用:

$(".parent div").not("div.1").wrapAll("<div class='sub'>");

Although, this will re-order your div s so that the wrap comes first, and the unwrapped element comes last. 虽然,这将对div重新排序,从而使包装首先出现,而未包装的元素最后出现。 Not a problem when it's the first element, but if it's the third, for example, the output would be: 当它是第一个元素时不是问题,但是例如,如果它是第三个元素,则输出将是:

<div class='sub'>
    <div class="1"></div>
    <div class="2"></div>
    <div class="4"></div>
    <div class="5"></div>
</div>
    <div class="3"></div>

Example: http://jsfiddle.net/tomtheman5/3TL4M/ 示例: http//jsfiddle.net/tomtheman5/3TL4M/

edit : Just saw @Corion's answer... This is essentially the same, but with some more information. 编辑 :刚刚看到@Corion的答案...这基本上是相同的,但是有更多信息。 I'll leave it up. 我留下来

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM