'create button dynamically by javascript and show variable content on click

I am creating button like this:

    if(this.error_msg) {
        let btn_err = document.createElement('button');
        btn_err.type = "button";
        btn_err.name = "add";
        btn_err.textContent = "Remove";
        btn_err.setAttribute("class", "btn btn-primary btn-sm");

        btn_wrapper.append(btn_err);

        toastBody.append(btn_wrapper);
    }        

How can I show this.error_msg on button click as alert?



Solution 1:[1]

You can add an event listener to the button using javascript.

btn_err.onclick = function(){alert(this.error_msg)}

Solution 2:[2]

You can do like this

Note: I have changed if argument as true since you did not share your whole code, it is just to show working example

const testFunction = () => {
  if(true) {
          let btn_err = document.createElement('button');
          btn_err.type = "button";
          btn_err.name = "add";
          btn_err.textContent = "Remove";
          btn_err.setAttribute("class", "btn btn-primary btn-sm");
          btn_err.onclick = function(){alert("Error message")}
          let btn_wrapper = document.getElementById("buttonWrapper")
          btn_wrapper.append(btn_err);
      }    
 }
 testFunction();
<div id="buttonWrapper">

</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Client
Solution 2 Evren