DEV Community

Cover image for Use a pseudo-element from CSS instead of toUpperCase method from JS
Evellyn Lima
Evellyn Lima

Posted on

2 2

Use a pseudo-element from CSS instead of toUpperCase method from JS

It's common to find a toUpperCase() method inside a JS file to transform a text into uppercase, sometimes this method is used to uppercase only the first letter from a sentence.

Does it work? Yes. Does is it the ideal? I believe it doesn't. In these cases, we are using JS to control some parts of our layout, and with this in mind, we should prioritize the use of CSS.

And, not by chance, only with CSS we can set the first letter to uppercase.
To solve this we need to use the ::first-letter pseud-element.

Let's use this HTML as example:

<p class="message">evellyn, your address was updated.</p>
Enter fullscreen mode Exit fullscreen mode

We have a paragraph with the class message with the text "evellyn, your address was updated.", the ideal is my name appears with the first letter as uppercase. Using CSS we can make it this way:

.message::first-letter {
  text-transform: uppercase;
}
Enter fullscreen mode Exit fullscreen mode

With it, we change the style only to the first letter from the selector message, now our sentence will appear as it should: "Evellyn, your address was updated."


JS allows us to make a lot of things, but sometimes it is not the right choice. It's always important to search how we can make that UI change using only CSS.


Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (2)

Collapse
 
maxart2501 profile image
Massimo Artizzu

If you want to capitalize every word in an element instead, text-transform: capitalize is your friend.

I always suggest to use CSS to transform to uppercase. It usually is meant to be a presentational transformation after all, so CSS is the right place to perform it when possible.

Collapse
 
evelew profile image
Evellyn Lima

Yep, I agree.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay