I have 2 HTML elements with 1000 child elements each. What is the best way to hind 1-st element and show 2-d, by using "display: none" or by removing and caching (in variable for the future recover) 1-st elements and inserting 2-d?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Excellent question. This gets to the heart of how browsers render web pages and is a crucial concept for writing performant web applications.
The short answer is: Using display: none is overwhelmingly the best way.
Let's break down why in detail.
TL;DR
Feature
display: none
Remove & Cache
Winner
Performance
Very Fast. A single style recalculation and repaint. The browser is highly optimized for this.
Very Slow. Triggers major DOM restructuring, causing expensive reflows/repaints.
display: none
Simplicity
Simple. Toggle a single CSS class.
Complex. Requires JavaScript to manage variables, remove nodes, and re-append them.
display: none
State Preservation
Preserves State. All child elements, their state (e.g., form input values), and their event listeners are kept intact.
Loses State. Direct event listeners on removed children are lost. Form data can be lost.
display: none
Memory
Uses more memory as elements remain in the DOM.
Uses less memory as elements are detached from the main DOM tree.
Remove & Cache
Conclusion: For your scenario with 1000 children, the performance and simplicity benefits of display: none far outweigh the minor memory cost.
Detailed Breakdown
Method 1: Toggling display: none (The Recommended Way)
This method involves changing the CSS display property of the element you want to hide. The best practice is to do this by adding or removing a CSS class.
CSS:
css
.hidden {
display: none;
}
HTML:
html
<div id="container1">
<!-- 1000 child elements -->
</div>
<div id="container2" class="hidden">
<!-- 1000 child elements -->
</div>
JavaScript:
javascript
const container1 = document.getElementById('container1');
const container2 = document.getElementById('container2');
function showContainer2() {
container1.classList.add('hidden');
container2.classList.remove('hidden');
}
function showContainer1() {
container2.classList.add('hidden');
container1.classList.remove('hidden');
}
What the browser does:
When you add display: none, the browser takes the element (and all its children) out of the render tree.
This means the element no longer participates in the page layout (reflow) or drawing (repaint). It takes up no space.
Crucially, the element and its children still exist in the DOM (Document Object Model). They are just not rendered.
Showing it again by removing the class is a very fast operation. The browser inserts it back into the render tree, triggering one reflow and repaint to make space for it and draw it.
Pros:
✅ Extremely Fast: This is what CSS is designed for. Browsers are heavily optimized to handle style changes efficiently.
✅ Simple & Declarative: The logic is clean and easy to understand.
✅ Preserves State: Any JavaScript event listeners attached to the children of container1 will still be there when you show it again. The values of any form fields inside it will also be preserved.
Cons:
❌ Memory Usage: The 2000 total child elements remain in the DOM, consuming memory. For this number of elements, this is a negligible concern on any modern device.
Method 2: Removing and Caching (The Inefficient Way)
This method involves physically removing the element from the DOM and storing it in a JavaScript variable to be added back later.
JavaScript:
javascript
const parent = document.body; // Or wherever the containers are
const container1 = document.getElementById('container1');
const container2 = document.getElementById('container2');
// Initially, remove container2 and cache it
let cachedContainer2 = container2.remove();
let cachedContainer1 = null;
function showContainer2() {
// 1. Remove container1 from the DOM
cachedContainer1 = container1.remove();
// 2. Insert the cached container2 into the DOM
parent.appendChild(cachedContainer2);
}
function showContainer1() {
// 1. Remove container2 from the DOM
cachedContainer2 = container2.remove();
// 2. Insert the cached container1 into the DOM
parent.appendChild(cachedContainer1);
}
What the browser does:
container1.remove(): This is a major DOM manipulation. The browser has to update the DOM tree, detaching 1001 nodes (the parent and its 1000 children). This triggers a reflow because the page layout changes.
parent.appendChild(cachedContainer2): This is another major DOM manipulation. The browser has to insert 1001 new nodes into the DOM. It then has to calculate the layout (reflow) and paint (repaint) for all of these new elements.
This process is significantly more work for the browser's rendering engine.
Pros:
✅ Lower Memory: The hidden element is not in the active DOM, so it consumes less memory. This is only relevant in extreme scenarios (e.g., hundreds of thousands of nodes on a very low-power device).
Cons:
❌ Terrible Performance: Directly manipulating thousands of DOM nodes is one of the most expensive operations you can perform in a browser. It will be noticeably slower and can cause the UI to freeze or jank.
❌ State is Lost: If you had attached event listeners directly to the children of container1 (e.g., child.addEventListener('click', ...)), those listeners are gone when you remove it. You would have to re-attach them every time you add it back, further hurting performance.
❌ More Complex Code: You have to manually manage the state and caching of the elements, which is more prone to bugs.
Conclusion
For your use case, and for 99.9% of all similar use cases, always prefer toggling a CSS class that sets display: none. It is faster, simpler, safer, and the standard, idiomatic way to show and hide elements on a web page. The "remove and cache" method should only ever be considered as a last resort in extreme memory-constrained situations where the hidden elements are exceptionally large and complex.