Create dynamic HTML button element with JavaScript/jQuery
This post will discuss how to generate an HTML button element in JavaScript and jQuery.
The HTML button element represents a clickable button that is often used to submit forms and implement standard button functionality anywhere on the document.
In vanilla JavaScript, you can use the document.createElement() method to programmatically create an HTML button element and set its required attributes. Then to append the button to a container, you can use the Node.appendChild() method.
This method is demonstrated below:
JS
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
document.addEventListener('DOMContentLoaded', function() { var button = document.createElement('button'); button.type = 'button'; button.innerHTML = 'Press me'; button.className = 'btn-styled'; button.onclick = function() { // … }; var container = document.getElementById('container'); container.appendChild(button); }, false); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container"></div> </body> </html> |
CSS
|
1 2 3 4 5 6 |
.btn-styled { font-size: 14px; margin: 8px; padding: 0 10px; line-height: 2; } |
If you work with jQuery, you may use the .append() method to append a button at the end of the specified container. Here’s a working example:
JS
|
1 2 3 4 5 6 7 8 9 |
$(document).ready(function() { $('#container').append( $(document.createElement('button')).prop({ type: 'button', innerHTML: 'Press me', class: 'btn-styled' }) ); }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container"></div> </body> </html> |
CSS
|
1 2 3 4 5 6 |
.btn-styled { font-size: 14px; margin: 8px; padding: 0 10px; line-height: 2; } |
Here’s a shorter version you can use:
JS
|
1 2 3 |
$(document).ready(function() { $('#container').append('<button class="btn-styled" type="button">Press me</button>'); }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container"></div> </body> </html> |
CSS
|
1 2 3 4 5 6 |
.btn-styled { font-size: 14px; margin: 8px; padding: 0 10px; line-height: 2; } |
Using .appendTo() method:
JS
|
1 2 3 |
$(document).ready(function() { $('<button class="btn-styled" type="button">Press me</button>').appendTo('#container'); }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container"></div> </body> </html> |
CSS
|
1 2 3 4 5 6 |
.btn-styled { font-size: 14px; margin: 8px; padding: 0 10px; line-height: 2; } |
That’s all about creating dynamic HTML button elements with JavaScript and Query.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)