how to capitalize for all first letters in javascript?

Dung Do Tien Aug 02 2021 654

Hello Guys, I am a newbie in Html & Javascript. I have a heading tag and a button and I want to capitalize for all first letters of heading tag when I click Change button. See the example below:

<h2>hello html and javascript</h2>
<button type="button"> Change </button>

If using CSS I know I can use text-transform: capitalize; to help capitalize. But I only want to use Javascript. How can I do it?

Thanks for any suggestions.

Have 3 answer(s) found.
  • Đ

    Đàm Ngọc Sơn Aug 02 2021

    You are making the complex a very easy thing. You can add this in your CSS:

    .capitalize-text {
        text-transform: capitalize;

    In JavaScript, you can add the class to an element by id:

    document.getElementById("element_id").className = "capitalize-text";
  • R

    Rubén Romero Cadena Aug 02 2021

    Oh, It's so easy. You can use javascript and add text-transform: capitalize; CSS for your heading tag. You can see an example below:

    <h2 id="heading">hello html and javascript</h2>
    <button type="button" onclick="ChangeUp()"> Change </button>
      function ChangeUp(){
        document.getElementById("heading").style="text-transform: capitalize;";

    You can run the above example here.

  • D

    Dương Trang Quốc Aug 02 2021

    You can try as below:

    const str = 'title of the document';
    function capitalize(str) {
       return str.charAt(0).toUpperCase() + str.slice(1);
    const caps = str.split(' ').map(capitalize).join(' ');

    You can run a demo here.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close