I am trying to execute specific JavaScript Code after Ajax Content Load. Please allow me to elaborate it. I have Following Code:-
index.html
<table>
<tbody id="tbody"></tbody>
</table>
script.js
// Ajax call, getting data from database
........
xhr.onload = () => {
x = xhr.response;
for (i = 0; i < x.length; i++) {
tbody.innerHTML += "<tr><td>" + x[i].name + "</td><td> <button class='btn btn-warning btn-sm btn-del' data-sid=" + x[i].id + ">Delete</button></td></tr>";
};
xhr.send();
// I want to execute below code after above ajax content load so i could get the length and can alert each button id
window.onload = function () {
var x = document.getElementsByClassName("btn-del");
console.log(x, x.length);
for (let i = 0; i < x.length; i++) {
alert(x[i].getAttribute("data-sid"));
}
};
//This works fine but This is not a good solution.
setTimeout(() => {
var x = document.getElementsByClassName("btn-del");
console.log(x, x.length);
for (let i = 0; i < x.length; i++) {
alert(x[i].getAttribute("data-sid"));
}
}, 2000);
I tried below codes but didn't get result as i am expecting:-
window.onload = function () { ......};
window.addEventListener("DOMContentLoaded", function () {.... });
document.onload = function () {...... };
if (document.readyState === 4) { ...... }
Note - I am trying to achieve this with Vanilla JavaScript so Please avoid Jquery