1

I'm using divs in JavaScript to test JavaScript's intersection observer api (https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API). I'm essentially testing how well it is able to detect divs when they enter the viewport. Another thing I'm trying to test is how well the intersection observer api deals with large amounts of divs. Currently all I have 30 manually duplicated divs like so:

<div id="one">1</div>
<div id="two">2</div>
<div id="three">3</div>
<div id="four">4</div>
<div id="five">5</div>

My aim is to really push this test & possibly have 500+ divs but it seems a bit silly thinking I must manually typing out 500+ divs. I was wondering if there is an easier way of achieving multiple divs of this amount? I've read around online & seen people speak of writing a script for it but no elaboration or examples available which would be helpful because I don't fully understand how that would work.

halfer
  • 19,824
  • 17
  • 99
  • 186
T.Doe
  • 1,969
  • 8
  • 27
  • 46

3 Answers3

0

You could use document.createElement.

Joshua M. Moore
  • 381
  • 6
  • 20
0

If you're using ES6 you can do something like:

Array.from({length: 500}, (v, k) => {
  const div = document.createElement('div'); 
  const text = k + 1; 
  div.appendChild(document.createTextNode(text));
  div.setAttribute("id", text) // this would be the tricky part...
  return div
})

to create an array of divs of size N = 500. The only part would be figuring out how to get the id attribute to convert from Number to String. There's a similar solution for that problem here:
Convert digits into words with JavaScript

Andrew Allison
  • 1,122
  • 2
  • 13
  • 30
0

Similar to the answers above, here is a quick fiddle:

const wrapper = document.getElementById("wrapper");

for(let i=0; i<500;i++)
{
    let el = document.createElement("div");
  el.classList.add("blu");
  el.innerHTML = "Div " + i;
  el.setAttribute("id", i);
  wrapper.appendChild(el);
}

https://jsfiddle.net/np49zjk1/13/

elasticman
  • 641
  • 8
  • 20