JSFiddle - React, Tailwind, and code Playground
HTML
<button id="addElements">Add an element</button>
<ul id="output"></ul>
CSS
button{
display: block;
}
ul{
padding: 0;
list-style:none;
}
li{
float:left;
background:#eceded;
display: block;
width: 1.5em;
height: 1.5em;
margin: .5em;
cursor: pointer;
}
JavaScript
// container is your content's container
var container = document.getElementById('output');
// Bind the Ajax function to the button
document.getElementById('addElements').addEventListener('click', addElement);
function addElement() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
container.insertAdjacentHTML('beforeend', xmlhttp.responseText);
}
}
xmlhttp.open("GET", "page.php", true);
xmlhttp.send();
}
// Delegate the click to container
container.addEventListener('click', makeMeRed);
function makeMeRed(event){
// If you clicked on an LI inside the container
if(event.target && event.target.nodeName == 'LI'){
event.target.style.background = 'red';
}
}
/* Just a fake XMLHttpRequest for the demo */
function XMLHttpRequest(){}
XMLHttpRequest.prototype.open = function(){};
XMLHttpRequest.prototype.send = function(){
var that = this;
setTimeout(function(){
that.readyState = 4;
that.status = 200;
that.responseText = '<li></li>';
that.onreadystatechange();
},200);
};