Split Divs into group with jquery

Asked

Viewed 355 times

2

Assuming I have 4 Divs whose class is "block". With jQuery would like to divide the Divs into blocks of 2, and "encompass" each set of "blocks" within another div.

I would like to make the code very dynamic, so that when adding several "blocks" automatically the jQuery divide and enter the div of contention.

EX::

Before the split

<div class="bloco"></div>
<div class="bloco"></div>
<div class="bloco"></div>
<div class="bloco"></div>

After the "split"

<div class="contain">
    <div class="bloco"></div>
    <div class="bloco"></div>
</div>
<div class="contain">
    <div class="bloco"></div>
    <div class="bloco"></div>
</div>

2 answers

2


Follows a solution using jQuery:

Html

<button id="btn">add blocos</button>

Javascript

function adicionarBlocosContencao() {

    //obtenho todos os elementos com a class .bloco e faço a varredura com each
    $('.bloco').each(function (inx) {

        //Verifico se o elemento já possui um contain
        if (!$(this).parent().hasClass('contain')) {

            //verifico se o numero é par, se for ele cria a div e adiciona a class container
            if (inx % 2 == 0) {
                $('body').append($('<div></div>')
                    .addClass('contain')
                    .append($(this)));
            } else {
                //se não for par só apendo no ultimo .container que não vai estar completo com 2
                $('.contain:last').append($(this));
            }
        }
    });
}

$(document).ready(function () {
    //setando evento de click no botão para chamar função
    $('#btn').click(adicionarBlocosContencao);
});

Follows the jsfiddle :)

  • Great code! I just need to understand which was the "magica" ai! I never used these "each, Parent, hasClass"

0

Considering:

<a href="#dividir">Click para dividir</a>

Using pure javascript:

var
  blocos = document.querySelectorAll('.bloco'),
  blocosLength = blocos.length,
  trigger = document.querySelector('a[href="#dividir"]');

trigger.addEventListener('click', function ( event ) 
{ 
  event.preventDefault();
  var
    blocosPorContain = ( blocosLength / 2 ),
    j = 0,
    i = 0,
    contain = {};

  for ( i; i < blocosLength; i++ ) 
  {
     j = j + 1;

     if ( j > blocosPorContain ) 
     { 
       j = 1;
     }
     else 
     {
       if ( j === 1 ) 
       {
         contain = document.createElement('div');
         contain.classList.add('contain');
       }
       contain.appendChild( blocos[ i ] ); 
       if ( j == blocosPorContain ) 
       {
         document.body.appendChild( contain );
       }
     }
  }
} );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.