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


HTML



Edit in JSFiddle

 
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


HTML



Edit in JSFiddle

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


HTML



Edit in JSFiddle

That’s all about changing the text of a button in JavaScript and jQuery.