Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
How to create DOM elements in JS memory-efficiently?

Consider the following code that inserts 100,000 spans with the content '0' inside.

<body>
    <script type="module">
        const container = document.getElementById('root')
        const CHILDREN_COUNT = 100000;

        for (let i = 0; i < CHILDREN_COUNT; i++) {
            const newChild = document.createElement("span");
            newChild.innerHTML = '0'
            container.appendChild(newChild)
        }
    </script>

    <div id="root" style="overflow-wrap: break-word">
    </div>
</body>

In my mind, after each loop, the garbage collection should clean up newChild as there are no further references to this var. The container itself I assume is a pointer to the DOM element, instead of being the entire thing in memory, and either way, should be cleaned after the loop executes.

However, testing reveals this page will take up 200,000kb~ of memory (per task manager in Chromium), but if CHILDREN_COUNT is reduced to 10, it takes up only c. 30,000kb~ of memory. Could the difference be entirely down to the DOM having to hold more span elements? Since the content for each span is minimal, I would have assumed not.

Is there something that I could do here to better manage memory use?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

check DocumentFragment -> https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment

 var list = document.querySelector('#list')
const CHILDREN_COUNT = 100000;
var fragment = new DocumentFragment();

        for (let i = 0; i < CHILDREN_COUNT; i++) {
          var spanEl = document.createElement('span');
          spanEl.innerHTML ='0';
          fragment.appendChild(spanEl);
        }
 
list.appendChild(fragment);

enter image description here

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!