+ 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?
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)
+ 5
But if you already have an onclick event, and want to modify it, you could use:
element.onclick = function() {};
(Although addEventListener is better)
+ 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";
+ 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>
+ 2
I get it, thanks a lot Airree