Mario Parra
Mario Parra

Reputation: 1554

Dynamically wrapping portion of divs with container

I have basic experience with DOM manipulation and jQuery, but I'm trying to figure out how to insert a new div container around the third and last divs within an existing container. The number of child divs will vary. I imagine I would use the nth-child selector, but I haven't gotten much further. I would manually add the new container, but the child divs are generated on page load. Thanks!

Existing structure:

<div id="primary-cont">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

Desired structure:

<div id="primary-cont">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div id="secondary-cont">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
  </div>
</div>

Upvotes: 0

Views: 32

Answers (3)

Uiupdates
Uiupdates

Reputation: 196

We can even use slice() jQuery method to do this.

 $('#primary-cont div.child').slice(3,6).wrapAll("<div class='secondary-count'></div>");

Upvotes: 0

andy jones
andy jones

Reputation: 922

Yes nth-child is the correct way to do this if you are using jQuery on the page, here is what i would do:

$('#primary-count .child:nth-child(n+4)').wrapAll( "<div id='secondary-cont'></div>" );

How does this work?

This will find the #primary-count div and then the .child inside of that, it will then childs there after, it will simply do 4 onwards.

However depending on how you are getting the content on the page this might not be the best way to do this, if you're in a php loop, it might be better to use that loop to insert the div

For example you could use something along these lines:

$count = 1;
foreach( $children as $child ) 
{
    if ($count%4 == 1)
    {  
         echo "<div>";
    }
    echo $kicks->brand;
    if ($count%4 == 0)
    {
        echo "</div>";
    }
    $count++;
}
if ($count%4 != 1) echo "</div>";

Upvotes: 1

Mario Parra
Mario Parra

Reputation: 1554

I built on Andy's answer and used .wrapAll() to achieve my desired structure:

$(document).ready(function() {
  $('#primary-cont .child:nth-child(n+4)').wrapAll('<div id="secondary-cont"></div>');
})

Upvotes: 0

Related Questions