Why does onClick event does not work if outerHTML is used?

111 Views Asked by At

Sample code below:

serviceQuerySnapshot.forEach(doc => {
                        
                        if(ownerIdNo === doc.data().shooter_id){
                            const servViewButton = document.createElement("button");
                            servViewButton.innerHTML = '<i class="fa fa-eye" aria-hidden="true"></i>';
                            servViewButton.style.marginRight = "5px";
                            servViewButton.style.border = "0";
                            servViewButton.style.background = "transparent";

                            servViewButton.onclick = async function() {

                                alert("wow");
                                console.error();
                            }

                            const servArrItem = ` · ${doc.data().name} ${servViewButton.outerHTML} ${'<br>'}`;
                            servArr += servArrItem;
        
                        }

                    });

As you can see here, I have an onclick event assigned to servViewButton and use servViewButton.outerHTML to display it next to the document name and add it to an Array but it seems like the onclick event is not working. The alert message is not prompting even after I click the button.

tried using addEventListener but the alert message still doesn't work.

What am I doing wrong here? Please help.

1

There are 1 best solutions below

1
Nicolò Pietro Oggiano On

Use addEventListener instead of click method and don’t use an async function. Try this:

servViewButton.addEventListener(“click”, () => { alert(“wow”); console.error(“error”)}