There are several div blocks:

<div class = "one"> </div> <div class = "two"> </div> <div class = "three"> </div> <div class = "four"> </div> <div class = "five"> </div> <div class = "six"> </div> 

Is it possible to select the first 2 elements first, then the second 2, etc. and create separate arrays for each pair or similarly, but with a large number of elements?

  • The html code removed, that's what I meant: div1 div2 div3 div4 div5 div6 - Maxim
  • you must first collect the entire collection, make .toArray and then splice 2 elements each. - nörbörnën

3 answers 3

Try using javascript method : slice .

The slice function takes 2 arguments: startIndex , endIndex and returns under the array.

An example of using slice .

If the length array is an even number, you can do this:

 var $divs = $('div'), startIndex = 0, resultArr = []; while(startIndex < $divs.length){ resultArr.push($divs.slice(startIndex, startIndex + 2)); startIndex += 2; } 

    I didn’t quite understand the question, but somehow:

     document.addEventListener('DOMContentLoaded', function() { var els = document.querySelectorAll('div'), i, array = []; for (i = 0; i < els.length; i += 2){ var tmp = []; tmp.push(els[i]); if (els[i + 1] !== undefined) tmp.push(els[i + 1]); array.push(tmp); } console.info(array); // Три массива будут в этом массиве - [[div, div], [div, div], [div]] }); 
     <div>Item 1</div> <div>Item 2</div> <div>Item 3</div> <div>Item 4</div> <div>Item 5</div> 

      I think something like this (if I understood correctly):

       var divs_el = document.getElementsByTagName('div');//Получаем div'ы (условно - в конкретном случае div'ы м.б. получены и по другому) var div2={};//Сюда будем "складывать" пары var d=0;//Для индесации пар var i=0;//Счетчик элементов var i_max = 2;//Каждые 2 элемента for(e in divs_el){ if(i==0){div2[d]=[];}//Если новая пара - создаем пременную для ее хранения (м.б. мссив или объект - что удонее) div2[d][i]=divs_el[e];//Записываем div в соответствующий массив i++;//Увеличиваем i if(i>=i_max){i=0; d++;}//Сбрасываем i для нового отсчета, (когда достигло двух) и увеличиваем на 1 d (переходим в след. следующий массив) } 

      As a result, we get a div2 object, with arrays of 2 divs in each. (All this, of course, can be written down and shorter. In addition, with the help of break and continue, if you wish, you can limit the selection)