Explain Codes LogoExplain Codes Logo

How to clear all s’ contents inside a parent ?

javascript
vanilla-javascript
performance
best-practices
Nikita BarsukovbyNikita Barsukov·Oct 14, 2024
TLDR

Instantly empty all child <div>s within a parent <div> by setting the parent’s innerHTML to an empty string:

// Knock knock. Who's there? Not the child divs' content, that's for sure 😂 document.querySelector('#parentDiv').innerHTML = '';

Ensure #parentDiv corresponds with your parent <div>'s ID to clear its content swiftly.

For those who like the conciseness of jQuery, there is an equally neat solution:

// Thanos snap, but for child divs' content 💥 $('#parentDiv').empty();

jQuery versus Vanilla JavaScript

While jQuery's syntax is concise, it's important to decide whether it exactly fits your needs. Using Vanilla JavaScript often fulfills the functionality with zero library loading.

Loop through child divs

A simple and efficient way to clear multiple child divs' contents is to iterate over them and set their innerHTML to an empty string:

// Prepare for the loop de loop 🎢 let childDivs = parentDiv.getElementsByTagName('div'); for (let div of childDivs) { // And...they're gone! 🎩🐇 div.innerHTML = ''; }

This for...of loop is modern, expressive and allows you to cycle neatly through child elements.

Considerations for other methods

If you are considering other methods such as .textContent = '' or .html(''), it's important to know the following:

  • Modifying .textContent or .innerHTML directly affects the layout and performance.

  • jQuery methods like .text('') and .html('') trigger internal processes for text or HTML parsing, making it less performant for clearing contents compared to the use of .empty().

Choosing the right method should consider your requirement on maintaining or removing event listeners entirely—context is key.