I want to select OKBTN
let main = document.querySelector("#main");
let okBtn = document.querySelector("#ok");
function myAlert(title,msg,icon){
let card = "";
card += `<div class="card">
<img src="${icon}.jpg">
<h1>${title}</h1>
<p>${msg}</p>
<button id="ok">OK</button>
</div>`;
main.innerHTML = card;
}
okBtn.addEventListener("click", function(){
main.style.display = "none";
});
myAlert("Title","MSG","icon")
Showing Error:
Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)
at imggal.html:88:5
2
Answers
Because the tag does not exist at first, it returns
undefined
I suggest putting the code inside a function and then hooking the event tag property to the function