JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="main"></div>
</body>
</html>
JavaScript
var customCallBack = () => {
console.log('any callback');
}
var waitForEl = function (selector, callback, maxTimes = false) {
console.log('attempt');
if (jQuery(selector).length) {
callback();
console.log('finished');
} else {
if (maxTimes === false || maxTimes > 0) {
(maxTimes != false) && maxTimes-- ;
setTimeout(function () {
waitForEl(selector, callback, maxTimes);
console.log('wasit again');
}, 100);
}
}
};
waitForEl('.new-el', customCallBack, 2); /* it will try 2 times to wait this element and then exist;
if you set 3 instead of 2, it will work because element will be attached to the DOM */
setTimeout(()=>{
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.className += "new-el";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";
document.getElementById("main").appendChild(div);
}, 300)