jQuery adds a new div element for each div element 3 and for each div element 6

advertisements

First all i'm new on jQuery so my question is not relevant please forgive me. I have some div elements in my Dom and i'm trying to make a book shelf for my products. I followed this fiddle and that works perfectly. But my products are coming from MySQL and i'm parsing them with foreach loop in PHP.

My HTML Looks like:

<div class="product-yarn col-xs-4 col-md-2">
  <a href="#" class="book-shelf"></a>
</div>
<div class="product-yarn col-xs-4 col-md-2">
  <a href="#" class="book-shelf"></a>
</div>
<div class="product-yarn col-xs-4 col-md-2">
  <a href="#" class="book-shelf"></a>
</div>
<div class="product-yarn col-xs-4 col-md-2">
  <a href="#" class="book-shelf"></a>
</div>
<div class="product-yarn col-xs-4 col-md-2">
  <a href="#" class="book-shelf"></a>
</div>
<div class="product-yarn col-xs-4 col-md-2">
  <a href="#" class="book-shelf"></a>
</div>

Question: How can i add new <div> element after each 3 <div> like;

<div class="col-xs-12 shelf hidden-md hidden-lg"></div>

And add new <div> element after each 6 <div> like;

<div class="col-xs-12 shelf"></div>

Shortly, desired HTML output;

<div class="product-yarn col-xs-4 col-md-2">
  <a href="#" class="book-shelf"></a>
</div>
<div class="product-yarn col-xs-4 col-md-2">
  <a href="#" class="book-shelf"></a>
</div>
<div class="product-yarn col-xs-4 col-md-2">
  <a href="#" class="book-shelf"></a>
</div>
<!-- Here Is The After 3rd div -->
<div class="col-xs-12 shelf hidden-md hidden-lg"></div>
<!-- Here Is The After 3rd div -->
<div class="product-yarn col-xs-4 col-md-2">
  <a href="#" class="book-shelf"></a>
</div>
<div class="product-yarn col-xs-4 col-md-2">
  <a href="#" class="book-shelf"></a>
</div>
<div class="product-yarn col-xs-4 col-md-2">
  <a href="#" class="book-shelf"></a>
</div>
<!-- Here Is The After 6th div -->
<div class="col-xs-12 shelf"></div>
<!-- Here Is The After 6th div -->

I looked at some questions in SO some of them about wrapping every 3 element with new element. But i want to add new element.

So, Is it possible to make it with jQuery?

Thanks in advance.

PS: Sorry for my bad English.


You need to use .after() in conjunction with :nth-child() Selector

.after()

Insert content, specified by the parameter, after each element in the set of matched elements.

:nth-child()

Selects all elements that are the nth-child of their parent.

Script

$(document).ready(function () {
    $(".product-yarn:nth-child(3n)").after('<div class="col-xs-12 shelf hidden-md hidden-lg">after 3th div</div>');
    $(".shelf:odd").removeClass('hidden-md hidden-lg');
});

DEMO