JSFiddle - React, Tailwind, and code Playground
HTML
<a href="#" id="add">Add</a>
<a href="#" id="repopulate">Repopulate</a>
<div id="container"></div>
JavaScript
var
// Array to hold elements in memory
elems = [],
// Id, which I will increment each time a new div is created
id = 0,
// Alias for document.getElementById
$ = function (id) { return document.getElementById(id); },
// Container, to hold divs
container = $("container"),
// Add button
addBtn = $('add'),
// Repopulate button
repopulateBtn = $('repopulate');
function add() {
// Create a new div element
var newElem = document.createElement('div');
// Add some text so we can identify it
newElem.appendChild(document.createTextNode('div' + (id++)));
// Add an event to test event handler
newElem.onclick = function () { alert("Click event works."); };
// Add it to my Array of elements (so it is stored in memory)
elems.push(newElem);
// And finally add it to the container
container.appendChild(newElem);
// Return false for event handler
return false;
}
function explicitClearContainer() {
var e;
// Explicitly remove all elements
for (var i = 0; i < elems.length; ++i) {
e = elems[i];
// Update the reference to the removed Node
elems[i] = e.parentNode.removeChild(e);
}
}
function repopulate() {
// Set container innerHTML to "pending"
container.innerHTML = 'repopulation pending, please wait 3 seconds';
// After 3 seconds, repopulate
setTimeout(function () {
// First, clear the container by clearing innerHTML
container.innerHTML = '';
// Then, add each of the elements from memory
for (var i = 0; i < elems.length; ++i) {
container.appendChild(elems[i]);
}
}, 3000);
// Return false for event handler
return false;
}
// Bind click events
addBtn.onclick = add;
repopulateBtn.onclick = repopulate;