Dhulfiqar
Dhulfiqar

Reputation: 29

How to change the heading (titles) text to uppercase?

I'm trying to change all the titles, i.e. h1, h2, h3... to be uppercase using JavaScript.

the white cat should be THE WHITE CAT.

The method will be placed in a seperate .js file.

Upvotes: 0

Views: 8667

Answers (4)

Thomas Darvik
Thomas Darvik

Reputation: 791

In JavaScript you need to get reference the object using document.getElementById or document.getElementsByClassName. After that you can style the element by accessing the style property of the object, OR just set the content to be uppercase using the built in toUpperCase() function that JavaScript has.

var header = document.getElementById("myHeader");
header.innerHTML = header.innerHTML.toUpperCase();
<h1 id="myHeader">Hello, world</h1>

HOWEVER

The easier solution is to just set a class on the whole header object, and use

.upperCaseHeader { text-transform: uppercase}

Or, if you know that all the header elements on your page will be uppercase, use;

h1,h2,h3,h4,h5 { text-transform: uppercase; }

in a CSS file.

EDIT: On OP's request the code is slightly changed to change the text to uppercase on button click

The function here will find all the tags of type h1 through h6 using getElementsByTagName and set all the text in them to uppercase, as you requested. Again, I would rather add a class with text-transform uppercase, and dynamically add and remove this class, but since you have very specific needs, I am posting this alternative solution here now.

Here is a working pen as well

function setUppercase() {
  var tags = ["h1", "h2", "h3", "h4", "h5", "h6"];
  for (var i = 0; i < tags.length; i++) {
    var allTagsOfType = document.getElementsByTagName(tags[i]);
    for (var j = 0; j < allTagsOfType.length; j++) {
      allTagsOfType[j].innerText = allTagsOfType[j].innerText.toUpperCase();
    }
  }
}
<h1>Hello</h1>
<h2>I am going</h2>
<h3>to be</h3>
<h4>uppercase</h4>
<h5>soon</h5>
<h6>tiny text</h6>
<button onclick="setUppercase()">Set uppercase</button>

Upvotes: 3

Christheoreo
Christheoreo

Reputation: 393

Perhaps something like this?
ref: https://www.w3schools.com/jsref/jsref_touppercase.asp

var text = $('h2').text();    
var res = text.toUpperCase();
$('h2').text(res); 

Edit-- Or you can do everything through JS and append the element. the `` are ES6 string literals.

var text = "The White Cat";    
var res = text.toUpperCase();
var uppercase = `<h2>${res}</h2>`;
$('body').append(uppercase);

Upvotes: 0

Gustavo Chagas
Gustavo Chagas

Reputation: 359

in your style.css

h2 {
text-transform: uppercase;
}

Upvotes: 0

Andrew I.
Andrew I.

Reputation: 252

Try this inline styling:

<h2 style="text-transform: uppercase"> The White Cate </h2>

Upvotes: -1

Related Questions