user2709207
user2709207

Reputation: 27

jquery get how many 'div' in each after 'h3' tag

i would like to know how many div that are in siblings with h3 tag located inside a parent div with the class content-block-infos-events

if some of the amount got less than 6 items, i would like to create divs tags so i can always reach to 6 items after each h3

for example :

<div class="content-block-infos-events" >
  <h3>H3 val</h3>
  <div class="views-row rows>
    TEXT 1
  </div>
  <div class="views-row rows>
    TEXT 2
  </div>
  // i have to add 4 another <div class="views-row rows>


  <h3>H3 val</h3>
  <div class="views-row rows>
    TEXT 1
  </div>
  <div class="views-row rows>
    TEXT 2
  </div>
  <div class="views-row rows>
    TEXT 3
  </div>
  <div class="views-row rows>
    TEXT 4
  </div>
  <div class="views-row rows>
    TEXT 5
  </div>
  <div class="views-row rows>
    TEXT 6
  </div>
  // no need to add the div because i have 6 divs
</div>

here you can find the html code : http://jsfiddle.net/Axdh6/2/

Upvotes: 1

Views: 1351

Answers (1)

Ram
Ram

Reputation: 144709

Instead of selecting siblings div elements which is not helpful in this case, you should iterate through the h3 elements and select their next siblings elements until the next h3 element.

$('.content-block-infos-events h3').each(function() {
    var $divs = $(this).nextUntil('h3'),
        div_count = $divs.length;
    if (div_count < 6) {
        var divs = '';
        for (var i = 0; i < (6 - div_count); i++) {
            divs += "<div class='views-row rows'>added-text</div>";
        }
        $divs.last().after(divs);
    }
});

http://jsfiddle.net/6s88v/

Upvotes: 1

Related Questions