How to add buttons to js | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

8th Feb 2017, 12:58 AM
Caleb Moore
4 Answers
+ 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
8th Feb 2017, 1:10 AM
nouha coding girl
nouha coding girl - avatar
+ 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 ;)
8th Feb 2017, 11:03 AM
visph
visph - avatar
+ 3
yes you can add buttons using JavaScript in HTML!! just like I did in one of my codes
9th Feb 2017, 12:33 AM
nouha coding girl
nouha coding girl - avatar
+ 1
thanks very much!
8th Feb 2017, 1:11 AM
Caleb Moore