Make First Letter Capital using CSS, JavaScript, and jQuery

There are a few different ways you can make the first letter of an element uppercase using CSS, JavaScript, and jQuery. In this article, we'll explore each of these methods and provide examples to help you understand how they work. First, we'll look at using CSS to make the first letter of an element uppercase. Then, we'll move on to using JavaScript and jQuery to achieve the same result. Whether you're working on a simple personal project or a larger professional website, these methods can come in handy when you want to add some style to your text.

Using CSS to Make First Letter Capital

To make the first letter of an element uppercase using CSS, you can use the ::first-letter pseudo-element. Here's an example:

.example {
  font-size: 20px;
}

.example::first-letter {
  text-transform: uppercase;
  font-size: 30px;
}

HTML Code:

<p class="example">hello, world!</p>

In the above example, the first letter of the p element with the class example will be uppercase and have a font size of 30px. The rest of the text will have a font size of 20px. Below is a live example:

See the Pen First Letter capital by Vinish Kapoor (@foxinfotech) on CodePen.

Using JavaScript to Capitalize First Letter

To make the first letter of an element uppercase using JavaScript, you can use the charAt method to get the first character of the element's text content, and then use the toUpperCase method to make it uppercase. Here's an example:

const element = document.querySelector('.example');
const text = element.textContent;
const firstLetter = text.charAt(0).toUpperCase();
const restOfText = text.slice(1);

element.textContent = firstLetter + restOfText;

HTML Code:

<p class="example">hello, world!</p>

In the above example, the first letter of the p element with the class example will be uppercase. Below is a live example:

See the Pen Untitled by Vinish Kapoor (@foxinfotech) on CodePen.

Using jQuery to Make First Letter Uppercase

To make the first letter of an element uppercase using jQuery, you can use the charAt method to get the first character of the element's text content, and then use the toUpperCase method to make it uppercase. Here's an example:

$('.example').text(function (index, text) {
  return text.charAt(0).toUpperCase() + text.slice(1);
});

HTML Code:

<p class="example">hello, world!</p>

In the above example, the first letter of the p element with the class example will be uppercase. Below is an example:

See the Pen Untitled by Vinish Kapoor (@foxinfotech) on CodePen.

Related:

Leave a Comment