sqarf sqarf - 6 months ago 57
jQuery Question

How do I count and even multiple divs child elements with same class in jquery

I want to make all "parent" elemens have 5 child elements. If "parent" div has less than 5 childs with class "child", I want to even them all out.

Here's example before:

<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>

<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>

<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>


This is how result should be:

<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>

<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>

<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>

Answer

First select all .parent and get content of every of them using each(). In loop you can calculating count of element that need to be added. 5 - count of exist child is count of element that need to be added.

$(".parent").each(function(){
    var length = $(this).children(".child").length;
    for (var i = 0; i < 5 - parseInt(length); i++){       
        $(this).append("<div class='child'>Added Child</div>");
    }
});
.parent {
    width: 100px;
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
    <div class="child">Child</div>
    <div class="child">Child</div>
    <div class="child">Child</div>
    <div class="child">Child</div>
</div>
<div class="parent">
    <div class="child">Child</div>
    <div class="child">Child</div>
    <div class="child">Child</div>
</div>
<div class="parent">
    <div class="child">Child</div>
    <div class="child">Child</div>
    <div class="child">Child</div>
    <div class="child">Child</div>
    <div class="child">Child</div>
</div>

Comments