Explain Codes LogoExplain Codes Logo

Append HTML to container element without innerHTML

javascript
dom-updates
performance-optimization
event-handling
Anton ShumikhinbyAnton Shumikhin·Jan 29, 2025
TLDR

document.createElement and appendChild are your friends for adding elements to the DOM. To convert HTML strings without using innerHTML, deploy DOMParser.

Example:

// Let's find a party, aka 'container' const container = document.querySelector('#container'); // Creates a new div, a VIP guest const elem = document.createElement('div'); // Says it's bringing 'New content' to the party elem.textContent = 'New content'; // Let's get the party started! container.appendChild(elem);

Don't like regular parties? Let's crash a string party!

// Also fancy, but we've got 'New content' in HTML attire. const html = new DOMParser().parseFromString('<div>New content</div>', 'text/html'); // The 'html' version has entered the party. container.appendChild(html.body.firstChild);

Content Append's got style

We are not always dealing with static content. More often, the real challenge arises with dynamic content, especially when media states and interaction needs to be in consideration. No worries, we've got some pro techniques for you.

Using insertAdjacentHTML

Think of insertAdjacentHTML as the smart genie that can place the new content exactly where you wish, in relation to a given element. This allows media playback to continue seamlessly and without any extra containment structure.

Example:

/* Before calling the genie, our party looked like this: #container { // 👇: Guests (Dynamic content) } */ // The genie is doing its job here: container.insertAdjacentHTML('beforeend', '<div id="newContent">The Genie 🧞 is here</div>'); /* After the genie's job, our party looks like this: #container { // 👇: Guests (Dynamic content) // 🧂👖🦀🕺: The Genie is here } */

The Power of DocumentFragment

DocumentFragment, imagine it as an invisible container that's lighter than a Document. It does its job like a secret agent, creates DOM nodes in memory stealthily, then inflates them into the document, all without leaving any trace (i.e., no extra tags) behind.

Example usage:

// Secret agent coming through let fragment = document.createDocumentFragment(); // Agent brings new party guest 'More info' fragment.appendChild(document.createElement('p').textContent = 'More info'); // Agent leaves, party gest bigger! container.appendChild(fragment);

One append operation to rule them all

Sometimes you have to control the venue. createElement and appendChild come to the rescue. They can provide a layer of granular control over the construction and placement of each node. These are perfect to create JavaScript controlled parties.

// Meticulously inviting each guest, one by one for (let i = 0; i < data.length; i++) { let item = document.createElement('div'); // Create invitation item.textContent = data[i]; // Writing name container.appendChild(item); // Send invitation }

Append HTML like a pro

Different strokes for different folks

Some tasks require you to append multiple elements. Performance matters. DocumentFragment can boost performance. insertAdjacentHTML and createElement + appendChild are super buddies and can optimize DOM updates.

Event Handling

Dynamic HTML often includes interactive elements that need to be handled. When appending such content, ensure to create event listeners to maintain functionality.

// Watch for gatecrashers! container.addEventListener('click', function(event) { if(event.target.matches('.interactive')) { // Handle event } });

The layout matters

Appending elements could affect your layout. Add CSS either inline or by adding classes to prevent unwanted changes. Manage styling of appended elements.

Performance

Appending HTML affects performance. And don't forget about security. DocumentFragment and proper encoding techniques ensure smooth performance and protection from injection attacks.