简体   繁体   中英

How to wrap a group of div inside a div

I have this html code:

<div id="elem">
    <div data-foo="aaa">a</div>
    <div data-foo="aaa">a</div>
    <div data-foo="aaa">a</div>
    <div data-foo="bbb">b</div>
    <div data-foo="bbb">b</div>
    <div data-foo="ccc">c</div>
    <div data-foo="ccc">c</div>
    <div data-foo="ccc">c</div>
    <div data-foo="ccc">c</div>
    <div data-foo="ccc">c</div>
</div>

I need to group all those different div[data-foo] inside a div like this:

    <div id="elem">
        <div class="wrap">
            <div data-foo="aaa">a</div>
            <div data-foo="aaa">a</div>
            <div data-foo="aaa">a</div>
        </div>
        <div class="wrap">
            <div data-foo="bbb">b</div>
            <div data-foo="bbb">b</div>
        </div>
        <div class="wrap">
            <div data-foo="ccc">c</div>
            <div data-foo="ccc">c</div>
            <div data-foo="ccc">c</div>
            <div data-foo="ccc">c</div>
            <div data-foo="ccc">c</div>
        </div>
    </div>

Those div[data-foo] contents are dynamically generated. I cant figure out how to solve this problem. Could someone help me please?

If you don't know the possible values, you may do this :

$('#elem [data-foo]').each(function(){
  var $this = $(this),
      $w = $(this).parent().find('.wrap:has([data-foo="'+$this.data('foo')+'"])');
  if (!$w.length) $w = $('<div>').addClass('wrap').appendTo($this.parent());
  $w.append(this);
});

try this...

PrevAttr= '';
        $('div#elem div').each(function(){

            attr = $(this).attr('data-foo');

            if(attr != PrevAttr)
            { PrevAttr = attr;
              $('div#elem div[data-foo='+attr+']').wrapAll('<div class="wrap"></div>')
            }
        })

Try this :

$(document).ready(function(){
   var array = [];
    // get all unique data-foo
    $('#elem div').each(function(){
      var fooData = $(this).data('foo');
      if($.inArray(fooData, array) ==-1)
         array.push(fooData); 
    });

    // wrap all unique data-foo divs in wrap div
    for(var i=0;i<array.length;i++)
    {
        $('[data-foo="'+array[i]+'"]').wrapAll("<div class='wrap'></div>");
    }
});

Working Demo

You can use .wrapAll() for that:

$('[data-foo="ccc"]').wrapAll("<div class='wrap'></div>");
$('[data-foo="bbb"]').wrapAll("<div class='wrap'></div>");
$('[data-foo="aaa"]').wrapAll("<div class='wrap'></div>");

Working Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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