+ 5

How to create or modify the 'onclick' event of an HTML element from js?

Hi everyone!! I'm very clear how to create and add an HTML element from js. window.onload = function() { //creating a new button var b = document.createElement("button"); var node = document.createTextNode("button"); //adding the text to the button b.appendChild(node); var div = document.getElementById("demo"); //adding the button to the div div.appendChild(b); }; https://www.sololearn.com/learn/JavaScript/2755/ Now ... how do I add or modify the 'onclick' event or any other parameter to it?

23rd Aug 2019, 4:28 PM
Yoel
Yoel - avatar
5 Réponses
+ 6
b.addEventListener("click", function(e){ //stuff to be done }); (you can also give a function name as parameter, that function then will be called)
23rd Aug 2019, 4:45 PM
Anton Böhler
Anton Böhler - avatar
+ 5
But if you already have an onclick event, and want to modify it, you could use: element.onclick = function() {}; (Although addEventListener is better)
23rd Aug 2019, 4:50 PM
Airree
Airree - avatar
+ 5
All elements have a style object, so you can do: document.querySelector("button").style["background-color"] = "blue"; And, some attributes can be accessed directly, like the class, as: element.className = "btn-class";
23rd Aug 2019, 5:57 PM
Airree
Airree - avatar
+ 2
Thanks Anton and Airree. But there is a new question 😀. That's in events case, how it would be to add the online style?? Ex: <button style="background-color:blue; color: #fff;"> Button </button> Or Its own class?? Ex: <button class="btn-class"> Button </button>
23rd Aug 2019, 5:41 PM
Yoel
Yoel - avatar
+ 2
I get it, thanks a lot Airree
23rd Aug 2019, 6:48 PM
Yoel
Yoel - avatar