0

I have a lot of elements like p, span, h1, h2. I don't know how much because it is dynamic. I need to separate elements into a div with 1000px height. So, I need to create multiple pages from one array, based on height.

for (let i = 0; i < items.length; i++) {
  $('.page').append(items[i]);
}

Elements example: items = [<ul class="ul1">..</ul>, <p class="p2">..</p>, <p class="p2">..</p>, <table>...</table>, <p class="p2">..</p>,<p class="p2">..</p>,<p class="p2">..</p>]

items have all HTML elements and it is dynamical, can have 10 or 100 elements. The idea is to return page1, page2, page3... etc, with 1000px and the elements. For now, I have one page with all the content.

3
  • Can you share the items array with us? These are not enough informations. Commented Jan 18, 2019 at 15:02
  • I edited my answer. Commented Jan 18, 2019 at 15:15
  • If I understand correctly just do $('.page').innerHTML = items[i]; instead of append. Don't forget to put each array element into single quotes. Commented Jan 18, 2019 at 15:16

1 Answer 1

1

You should precise a little bit more your problem but here is a possibility (to adapt to your case).

I assume that items is an array of jQuery elements (so i am calling .height())...

EDIT: your edit shows an array of HTML elements, you can convert it into jQuery elements doing e.g items = items.map(item => $(item))

let pageInd = 1

// loop over each page
while (items.length) {

  let // stores the items of the current page
      curPageItems = []
  ,   // current page height
      height = 0

  // loop over each elements of the current page
  curPageElmts: while (items.length) {

    // get the next element
    const nextElmt = items.shift()

    // update height
    height += nextElmt.height()

    // break loop if the height goes over 1000px
    if (height > 1000) break curPageElmts

    // otherwise add it to the current page
    curPageItems.push(nextElmt)

  }

  // append those items in the corresponding page
  // (jQuery accepts appending arrays of elements)
  $(`.page-${pageInd++}`).append(curPageItems)

}

You can also avoid the last line and store the result in a new Array.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer, I will try.
@JavierMolinasVilas i edited my code (which first was wrong sorry) since .height() was processed 2 times by item, which is bad
This works but not as I expected, because the pages have more than 1000px. The second page has 400px and finally, the content changed the position. I need to investigate. Thanks for all!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.