1

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>
3

4 Answers 4

2

I think this should make it:

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

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

2

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');

Comments

0

<!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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.