+ 1
How to add buttons to js
so I am coding this thing with js and it needs buttons but I don't know the code in how to do it can you help?
4 odpowiedzi
+ 6
hello , this is a code how to create buttons using js !!
// 1. Create the button
var button = document.createElement("button");
button.innerHTML = "Do Something";
// 2. Append somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
// 3. Add event handler
button.addEventListener ("click", function() {
alert("did something");
});
/* Read
+ 3
To be accurate:
You doesn't "add buttons to js", but exactly you add buttons to html... This is why you quickly need to know at least basics of html for use it as a GUI.
Alternatively to @coding girl solution, you can 'write' directly html source code in document and/or in a particular html element to update its html text content:
document.write('<button onclick="alert('did something');">Do Something</button>');
var e = document.getElement.getById('someId');
e.innerHTML = '<button onclick="alert('did something');">Do Something</button>';
... second method is preferable, as first could overwrite the actual page source content, and the property 'innerHTML' is as well readable as writable ;)
+ 3
yes you can add buttons using JavaScript in HTML!! just like I did in one of my codes
+ 1
thanks very much!