skip to Main Content

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


  1. Chosen as BEST ANSWER
    **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");
    }
    

  2. 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="handleClick(e)">OK</button>
        </div>`;
        
        main.innerHTML = card;
    }
    
    const handleClick = e => {
    main.style.display = "none";
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search