Categories
JavaScript Answers

How to set button text via JavaScript?

Spread the love

Sometimes, we want to set button text via JavaScript.

In this article, we’ll look at how to set button text via JavaScript.

How to set button text via JavaScript?

To set button text via JavaScript, we set the textContent property.

For instance, we write

const b = document.createElement("button");
b.textContent = "test value";

const wrapper = document.getElementById("divWrapper");
wrapper.appendChild(b);

to create a button with createElement.

The we set its text by setting the textContent property.

Then we get the parent of the button with getElementById.

And finally we call wrapper.appendChild with b to add the button as the last child of the wrapper.

Conclusion

To set button text via JavaScript, we set the textContent property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *