Jimbo Jambo
Jimbo Jambo

Reputation: 39

How can I close a div tag and open a new one after a number of content elements using jquery?

I have a div container (containing child elements), that needs to be splitted in several ones (depending on content length)

<div class="box">
    <p>Element 1</p>
    <p>Element 2</p>
    <p>Element 3</p>
    <p class="here">Element 4</p>
    <p>Element 5</p>
    <p>Element 6</p>
</div>

I've already tried insertBefore():

$('</div></div class="box">').insertBefore($('.here'));

But this makes something like that (what I don't understand):

<div class="box">
    <p>Element 1</p>
    <p>Element 2</p>
    <p>Element 3</p>
    <div class="box"></div>
    <p class="here">Element 4</p>
    <p>Element 5</p>
    <p>Element 6</p>
</div>

I'm in need to split my 'box' container in several ones. Is there any other way to manage this, to get it like that?

<div class="box">
    <p>Element 1</p>
    <p>Element 2</p>
    <p>Element 3</p>
</div>
<div class="box">
    <p class="here">Element 4</p>
    <p>Element 5</p>
    <p>Element 6</p>
</div>

Background: The content height of each <p> is added. When a specific total height is reached, I need to close the current and open a new 'box' div.

I've also read similar threads without finding (or maybe understanding) any solution for my problem.

Upvotes: 0

Views: 90

Answers (2)

Nima Shahin
Nima Shahin

Reputation: 43

You can use wrap property! For example :

$(".here").wrap( "<div class="box"></div>");

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370769

Use appendTo to append the new .box to the body, then use .append to move all elements that are .here or come after .here to that new .box:

$('<div class="box"></div>')
  .appendTo('body')
  .append($('.here, .here ~ *'));
.box {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
  <p>Element 1</p>
  <p>Element 2</p>
  <p>Element 3</p>
  <p class="here">Element 4</p>
  <p>Element 5</p>
  <p>Element 6</p>
</div>

Upvotes: 1

Related Questions