Explain Codes LogoExplain Codes Logo

Inserting HTML elements with JavaScript

javascript
html-insertion
document-fragment
template-management
Anton ShumikhinbyAnton Shumikhin·Aug 13, 2024
TLDR

Immediate insertion of an HTML element using JavaScript:

// Create <div> with 'Hello, World!' and stick it into the body like a festival poster document.body.appendChild(Object.assign(document.createElement('div'), {textContent: 'Hello, World!'}));

You can also mass insert elements more efficiently with document fragments:

// Create the mother of all fragments to host your elements const fragment = document.createDocumentFragment(); fragment.appendChild(document.createElement('p')); // VIP Section fragment.appendChild(document.createElement('section')); // Food Court document.body.appendChild(fragment); // Boom! Instant concert venue!

Advanced content insertion techniques

Multitasking with document fragments

If you're adding multiple elements, consider document fragments to prevent repetitious page reflows (pssst...it's analogous to a superhero doing chores):

let fragment = new DocumentFragment(); // Task list of a superhero fragment.appendChild(document.createElement('ul')); // Fetch groceries // Add more chores to the list document.getElementById('target').appendChild(fragment); // Jobs done!

Raw HTML insertion with insertAdjacentHTML

Raw HTML? No problem, insertAdjacentHTML to the rescue. Because sometimes, you just need to insert raw HTML into your doc:

document.getElementById('target').insertAdjacentHTML('beforeend', '<span>New content</span>'); // Walked right into the party!

Template element cloning and customization

Make your life easier—clone existing elements, customize them, and reinsert:

let template = document.getElementById('template').cloneNode(true); // Presto, a clone! template.id = 'newId'; // Let's make it stand out with a new ID. Sophistication matters. document.body.appendChild(template); // Welcome to the family, champ!

Precise positioning with insertAdjacentHTML

With insertAdjacentHTML(), position your new elements with the precision of a surgeon:

  1. 'beforebegin': Before the target element. Be the first!
  2. 'afterbegin': Inside target, before its first child. First kid rules!
  3. 'beforeend': Inside target, after its last child. The last kid gets all the love.
  4. 'afterend': After the target element. Baby of the family!

Here's an example:

// Inserting before an element like cutting in line at a fast food joint targetElement.insertAdjacentHTML('beforebegin', '<p>Paragraph inserted before</p>'); // Classic case of skipping ahead. Inserts after the element targetElement.insertAdjacentHTML('afterend', '<footer>New footer</footer>');

Template management in a hidden DIV

For frequent template reuse, shield the template in a hidden div. Improve performance and say goodbye to redundancy:

let templateDiv = document.getElementById('hiddenTemplateDiv'); // Laser locked hidden treasure let nodeToClone = templateDiv.firstElementChild; // First born let clonedNode = nodeToClone.cloneNode(true); // Clone created. Welcome, new entity! clonedNode.id = 'newUniqueID'; // Special treatment with a unique ID document.body.appendChild(clonedNode); // Let's show off the newbie!

The careful art of table elements

Creating table elements demands special care. The process is simply irreplaceable:

let table = document.createElement('table'); // A majestic table let tbody = table.createTBody(); // Time to create the heart of the table let row = tbody.insertRow(); // Let's add a row and spice things up let cell = row.insertCell(); // Can't have empty seats! cell.textContent = 'Table cell text'; // Giving it life document.body.appendChild(table); // Bring out the table!