Reputation: 7
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
Upvotes: -1
Views: 77
Reputation: 26
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
let main = document.querySelector("#main");
function myAlert(title,msg,icon){
let card = "";
card += `<div class="card">
<img src="${icon}.jpg">
<h1>${title}</h1>
<p>${msg}</p>
<button id="ok" onclick="e => handleClick(e)">OK</button>
</div>`;
main.innerHTML = card;
}
const handleClick = e => {
main.style.display = "none";
});
Upvotes: 0
Reputation: 7
**NOW ITS WORKING FINE**
let main = document.querySelector("#main");
let btn = document.querySelector("#btnMyAlert");
function myAlert(title,msg,icon){
let card = "";
card = `<div class="card">
<img src="${icon}.jpg">
<h1>${title}</h1>
<p>${msg}</p>
<button id="ok" onclick="handleClick()">OK</button>
</div>`;
main.innerHTML = card;
}
const handleClick = () => {
main.style.opacity = 0;
};
btn.onclick = () => {
main.style.opacity = 1;
myAlert("Title","MSG","icon");
}
Upvotes: 0