Immediate insertion of an HTML element using JavaScript:
// Create <div> with 'Hello, World!' and stick it into the body like a festival posterdocument.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 elementsconst fragment = document.createDocumentFragment();
fragment.appendChild(document.createElement('p')); // VIP Sectionfragment.appendChild(document.createElement('section')); // Food Courtdocument.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 superherofragment.appendChild(document.createElement('ul')); // Fetch groceries// Add more chores to the listdocument.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:
'beforebegin': Before the target element. Be the first!
'afterbegin': Inside target, before its first child. First kid rules!
'beforeend': Inside target, after its last child. The last kid gets all the love.
'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 jointtargetElement.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 treasurelet nodeToClone = templateDiv.firstElementChild; // First bornlet clonedNode = nodeToClone.cloneNode(true); // Clone created. Welcome, new entity!clonedNode.id = 'newUniqueID'; // Special treatment with a unique IDdocument.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 tablelet tbody = table.createTBody(); // Time to create the heart of the tablelet row = tbody.insertRow(); // Let's add a row and spice things uplet cell = row.insertCell(); // Can't have empty seats!cell.textContent = 'Table cell text'; // Giving it lifedocument.body.appendChild(table); // Bring out the table!