Change text of a button with JavaScript/jQuery
This post will discuss how to change the text of a button in JavaScript and jQuery.
The button element is now preferred way to create buttons over <input> element of type button. There are several ways to change the button‘s label text, which is inserted between its opening and closing tags.
1. Using jQuery
With jQuery, you can use the .text() method to replace the button‘s label text. This is demonstrated below:
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $(this).text('Processing…'); }) }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <button id="submit">Submit</button> </body> </html> |
Note that the .text() method will escape the provided text as necessary to render correctly in HTML.
Alternatively, you can use jQuery’s .html() method to replace an element’s content with the new content completely. It uses the browser’s innerHTML property and doesn’t escape the provided text, leading to cross-site security attacks.
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $(this).html('Processing…'); }) }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <button id="submit">Submit</button> </body> </html> |
2. Using JavaScript
In pure JavaScript, you can use either innerHTML, innerText or textContent to write text inside an element. Among them, textContent has better performance because its value is not parsed as HTML, and it also prevents XSS attacks.
JS
|
1 2 3 |
document.getElementById('submit').onclick = function() { this.textContent = 'Processing…'; } |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <button id="submit">Submit</button> </body> </html> |
That’s all about changing the text of a button in JavaScript and jQuery.
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 :)