I have a group of divs arranged in a grid.
To style each div I\'m selecting them with the nth-child() pseudo-class.
div.tile:nth-child(4n-7)
I suggest still using detach. You can do so with this code:
var divs;
$('.hide-divs').on('click', function () {
if(divs) {
$(divs).appendTo('.row');
divs = null;
} else {
divs = $('.dolphin').parent().detach();
}
});
Then to ensure that the same order is used, I came up with this bit of code:
$('.tile').each(function(i){
$(this).data('initial-index', i);
});
...
$(divs).each(function(){
var oldIndex = $(this).data('initial-index');
$('.tile').eq(oldIndex).before(this);
});
Put it all together and we get this code:
var divs;
$('.tile').each(function(i){
$(this).data('initial-index', i);
});
$('.hide-divs').on('click', function () {
if(divs) {
$(divs).appendTo('.row').each(function(){
var oldIndex = $(this).data('initial-index');
$('.tile').eq(oldIndex).before(this);
});
divs = null;
} else {
divs = $('.dolphin').parent().detach();
}
});
Demo on jsfiddle: http://jsfiddle.net/tqbzff2v/2/