Explain Codes LogoExplain Codes Logo

Add/remove HTML inside div using JavaScript

javascript
event-delegation
dom-interactions
performance-optimization
Anton ShumikhinbyAnton Shumikhin·Jan 24, 2025
TLDR
// To insert new HTML, HTML += is your new best mate: document.querySelector('#yourDiv').innerHTML += '<p>Add this</p>'; // To clean the house and remove everything inside, HTML = '' is the new vacuum cleaner: document.querySelector('#yourDiv').innerHTML = '';

With innerHTML += you add items to a div, while innerHTML = '' is like pressing a reset button on everything within.

Optimize DOM interactions for Performance

Efficient Element Creation and Addition

The createElement and appendChild methods are a performer's choice when it comes to adding new elements to the DOM:

// createElement is the stork delivering your new bundle of joy let newElement = document.createElement('div'); // appendChild is the welcoming party for the new arrival container.appendChild(newElement);

Swift Element Removal

To remove an element, go straight to its parent without disturbing the rest of the family:

// It's not you, it's your parent! elementToRemove.parentNode.remove(elementToRemove);

The Art of Clean-up

Keep the DOM clean. When adding or taking away elements, ensure any event listeners are tidied up with the mess:

// Goodbye listener, you have served us well! elementToRemove.removeEventListener('click', yourEventHandler); // Now, you are free to go! elementToRemove.remove();

Event Delegation and Dynamic Elements

All Ears for Event Delegation

Let the div handle the child-rearing. Event delegation allows you to manage events in one central location, preserving resources:

// Let the parent do the talking document.getElementById('yourDiv').addEventListener('click', function(event) { if (event.target.classList.contains('remove-btn')) { // 'Remove thyself!' - William JavaScript event.target.closest('.row').remove(); } });

Assign Identification for Better Control

Easy-to-identify elements help in manipulation and also lend a hand in adding visual styles:

// Creating a unique snowflake... newElement.className = 'dynamic-content'; newElement.id = `content-${uniqueId}`;

Rely on unique IDs so the DOM won't mix up who's who!

Advanced Techniques and Things to Watch Out

Timely HTML Insertion with insertAdjacentHTML

Want to be precise with positioning? insertAdjacentHTML lets you specify the location of injection:

// It's all about location, location, location! document.getElementById('yourDiv').insertAdjacentHTML('beforeend', '<div>Even More Content</div>');

Consistent Styling

Uniform class name for dynamically added elements helps maintain a consistent look and feel:

// Dress for the DOM you want! newElement.classList.add('consistent-style');

Handy Functions for Row Addition and Removal

Make your life (and code) easier by packing your logic into neat little functions:

// Call me for a birthing session! function addRow() { /* New row code here */ } // Summon me for a clean-up! function removeRow(rowId) { /* Row removal code here */ }

Event Listener Cleanup

Prevent memory leaks by cleaning up listeners for elements that no longer exist:

// You don't live here anymore, now shoo! document.querySelector('.dynamic-content').forEach(elem => { elem.removeEventListener('click', yourEventHandler); });