Can I $.wrap() around a collection of elements in an array?

后端 未结 3 1444
长情又很酷
长情又很酷 2021-02-09 00:07

Let\'s say I have a collection of \'items\' like so:

3条回答
  •  我寻月下人不归
    2021-02-09 00:52

    You can use a combination of .filter and .map to achieve the desired result:

    $(".item.group")
    .filter(function() {
        return !$(this).prev().is(".group");
    })
    .map(function() {
        return $(this).nextUntil(":not(.group)").andSelf();
    })
    .wrap('
    ');

    See it in action.

    Example on JS Bin to get around the current JSFiddle problems.

    Rationale

    The method .wrap embeds each item inside the current jQuery object inside the markup of your choice. It follows that if you want to wrap multiple elements in the same wrapper you have to match those N elements with a jQuery object and then create another jQuery object that contains one element: the first jQuery object. It is this latter object that you should pass to .wrap.

    So what we need to do here is create one jQuery object for each group and then put all of those into another "master" jQuery object. Begin by selecting all .group elements that are not themselves preceded by a .group sibling:

    $(".item.group")
    .filter(function() {
        return !$(this).prev().is(".group");
    })
    

    From each such element, create a jQuery object that includes the element and all following siblings with .group:

    .map(function() {
        return $(this).nextUntil(":not(.group)").andSelf();
    })
    

    The resulting jQuery objects are automatically placed inside the "master" object because they take the place of the bare elements we selected with .filter inside the jQuery object we created with $(".item.group"). A final call to .wrap... wraps things up. :)

提交回复
热议问题