pexichdu pexichdu - 4 months ago 8
HTML Question

Add div jquery in loop

so when I selected some of the div like this

var filter = $('.album1.phonepic');


I want to add them in to an empty I div already have, but only 4 for each one.

<div class="emptydiv1"></div>
<div class="emptydiv2"></div>
var count = 0;

for(var i = 0; i <= filter.length; i++){
if(count <= 4){
$('.emptydiv1').append(filter[i]);
count++;
}else {
$('.emptydiv2').append(filter[i]);
}
}


whenever I try to loop the selected variables its not working. Please help me

Answer

Here some simple code that will work for you

var filter = $('.album1.phonepic');

for (var i = 0; i <= filter.length; i++) {
    var emptyDiv = i < 4?$('.emptydiv1'):$('.emptydiv2');
    emptyDiv.append(filter[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="album1 phonepic">Test 1</span>
<span class="album1 phonepic">Test 2</span>
<span class="album1 phonepic">Test 3</span>
<span class="album1 phonepic">Test 4</span>
<span class="album1 phonepic">Test 5</span>
<span class="album1 phonepic">Test 6</span>
<span class="album1 phonepic">Test 7</span>
<span class="album1 phonepic">Test 8</span>

<hr/>
<div class="emptydiv1">div 1</div>
<hr/>
<div class="emptydiv2">div 2</div>

or another way using :lt() and :gt:()

var albums  = $('.album1.phonepic');
   

$('.emptydiv1').append(albums.filter(':lt(4)'))
$('.emptydiv2').append(albums.filter(':gt(3)'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="album1 phonepic">Test 1</span>
    <span class="album1 phonepic">Test 2</span>
    <span class="album1 phonepic">Test 3</span>
    <span class="album1 phonepic">Test 4</span>
    <span class="album1 phonepic">Test 5</span>
    <span class="album1 phonepic">Test 6</span>
    <span class="album1 phonepic">Test 7</span>
    <span class="album1 phonepic">Test 8</span>

<hr/>
    <div class="emptydiv1">div 1</div>
<hr/>
    <div class="emptydiv2">div 2</div>

Comments