mohsen mehri
mohsen mehri

Reputation: 41

How to set onclick for element when created with javascript

How can i set the onclick property for an element like link or button when it's created with Javascript or how can i set an eventListener?

I create the Button with JavaScript, set an Id and add a Class.

var button=document.createElement('button')
button.className="btn btn-sm btn-danger listening_class_for_delete"
button.appendChild(delete_text_button)
button.setAttribute('id',id);
// how can i set 'onclick' here
// output shall be: 
<button ... onClick="functionName"></button>

Upvotes: 1

Views: 3153

Answers (4)

biberman
biberman

Reputation: 5777

Since you are using javascript you can add the onclick event listener directly to your script:

button.addEventListener('click', functionName);

If it is important for you to have it in the tag you can do the following with javascript:

document.querySelector('#button').setAttribute('onclick', 'functionName');

Upvotes: 2

Force Bolt
Force Bolt

Reputation: 1221

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="div"></div>
    <script>
      window.onload = () => {
        let div = document.getElementById("div");
        var button = document.createElement("button");
        button.innerText = "Click here";
        button.className = "btn btn-sm btn-danger listening_class_for_delete";
        div.appendChild(button);
        button.setAttribute("id", "id");
        button.addEventListener("click", () => {
          let p = document.createElement("p");

          p.innerText = "Clicked";

          div.appendChild(p);
        });
      };
    </script>
  </body>
</html>

Upvotes: 0

AlexxBoro
AlexxBoro

Reputation: 449

you can add an onclick function to your button element like so:

1.

button.onclick = () => {
  alert("onclick 1!");
};
button.addEventListener("click", ()=>{alert("onclick 2!")}, false);

Upvotes: 2

Zniets
Zniets

Reputation: 33

I think this should make it:

document.getElementById(id).onclick = function() { }

Upvotes: 2

Related Questions