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

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.

Upvotes: 0

Views: 137

Answers (1)

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

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

Upvotes: 0

Related Questions