Chamara Keragala
Chamara Keragala

Reputation: 5777

jQuery Wrapp unique Elements

Following are the tags which have been created.

<div class="2013"><p>Item 1</p></div>
<div class="2013"><p>Item 2</p></div>
<div class="2012"><p>Item 3</p></div>
<div class="2012"><p>Item 4</p></div>
<div class="2012"><p>Item 5</p></div>
<div class="2011"><p>Item 6</p></div>

I need to arrange them as the following using jQuery.

<div id="2013">
    <div class="2013"><p>Item 1</p></div>
    <div class="2013"><p>Item 2</p></div>
</div>
<div id="2012">
    <div class="2012"><p>Item 3</p></div>
    <div class="2012"><p>Item 4</p></div>
    <div class="2012"><p>Item 5</p></div>
</div>
<div id="2012">
    <div class="2011"><p>Item 6</p></div>
</div>

Upvotes: 0

Views: 57

Answers (2)

bipen
bipen

Reputation: 36541

using each and wrapAll()

try this..

var tempObj={};
$('div').each(function(){
  var className=this.className;
  tempObj[className]=className;
});
$.each(tempObj,function(i,v){
  $('.'+v).wrapAll('<div id="'+v+'"></div>')
});

fiddle here

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388406

Try

//here find out the divs you want to target - this filter is for demo only
var $targets = $('div');

var classes = {};
$targets.each(function(){
    classes[this.className] = this.className;
})

$.each(classes, function(key, value){
    $targets.filter('.' + key).wrapAll($('<div />', {
        id: key
    }))
})

Demo: Fiddle

Upvotes: 6

Related Questions