JavaScript: Programmatically Create an HTML Button
In this tutorial, we will learn how to create an HTML button element programmatically with JavaScript and add it somewhere in the document.
Create HTML Button with JavaScript
To create an HTM button element with JavaScript, use the document.createElement()
function and pass button as the first argument like this:
var btn = document.createElement('button');
Customize Button Text, ID & Class
Now a button element has been created, let's add some text, assign an ID and a class to it.
btn.id = 'send';
btn.classList = 'btn-success';
btn.innerHTML = 'Send Now';
console.log(btn.id);
console.log(btn.classList);
console.log(btn.innerHTML);
send
btn-success
Send Now
Adding ID and class attributes is optional but in most cases, you'll be doing this.
Add Button to the Document
Now let's add the new button to the HTML document. To demonstrate this, we'll append the button to a div attribute with the ID of wrapper.
<div id="wrapper"></div>
document.getElementById('wrapper').append(btn);
The final HTML output of the button we added will look like this:
<button id="send" class="btn-success">Send Now</button>
Full Adding HTML Button to Page Example
Here is the full example for reference:
var btn = document.createElement('button');
btn.id = 'send';
btn.classList = 'btn-success';
btn.innerHTML = 'Send Now';
document.getElementById('wrapper').append(btn);
Conclusion
Now you have added a button on the page you may need to detect when it is clicked and do something in JavaScript. Please read my article on how to add an event listener in JavaScript.