Lets say that in this case i have 4 divs called ".CountThese" and i wanted to do just that, get the number of elements with that specific class and then append a div as many times as was the amount of ".CountThese" ( 4 times in this case )
This is the html:
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="appendHere"></div>
This would be the result:
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="appendHere">
<div class="appendedDIVs"></div>
<div class="appendedDIVs"></div>
<div class="appendedDIVs"></div>
<div class="appendedDIVs"></div>
</div>
I got only so far that i found out that you can count number of elements something like this:
function divcount() {
var Count = $('.CountThese').length();
document.write(Count)
}
thought i dont necessarily know how to use that.. i seriously have no idea how i could then use that number to append divs or anything else for that matter..
How can this be achieved?
The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend() ).
jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.
You can avoid the manual iteration by using the array join()
method like:
$(".appendHere").append(new Array(++n).join('<div class="appendedDivs">New!</div>'));
Where n is the number of elements you want to create.
This is better than the accepted answer since it only manipulates the DOM once rather than n
times.
var n = $(".CountThese").length;
$(".appendHere").append(new Array(++n).join('<div class="appendedDivs">New!</div>'));
.CountThese {
display: inline-block;
width: 46px;
height: 50px;
background: royalblue;
}
.appendedDivs {
display: inline-block;
height: 30px;
line-height: 30px;
padding: 5px;
margin-right:5px;
color: gold;
font-weight: bold;
background: dodgerblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="appendHere"></div>
You can iterate over the .CountThese divs and for each one, append to .appendHere
$('.CountThese').each(function(){
$('.appendHere').append('<div class="appendedDivs"></div>');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With