Capitalise the first letter of a group of words quickly & easily

Sometimes as a web developer I have to capitalise the first letter of each word normally for title and header tags but I don’t want to have to sit there manually capitalising each letter. HTML and CSS don’t have a native feature which allows you to quickly capitalise the first letter automatically so we have to look at using JavaScript to achieve this.

This example uses jQuery a JavaScript library which extends the capabilities of JavaScript.

It is best to place this code in the <head></head> tags after the jQuery library include link.

The following code will capitalise the first letter of each word which is in a header tag. A header tag looks like the following h1, h2, h3, h4, h5 and h6.

$(document).ready(function() {
      $(":header").each(function(){
            html = '';
            words = $(this).text().split(' ');
            $.each(words, function(){
                  html += '' + this.substring(0,1) + '' + this.substring(1) + ' ';
            });
            $(this).html(html);
      });
});

You can change the elements which are capitalised by adjusting the following line.

$(":header").each(function(){

If you want to capitalise the first letter of each word within a “h1” tag change it to the following.

$("h1").each(function(){

If you want to capitalise the first letter of each word which is within a element with a class of “title” change it to the following.

$(".title").each(function(){

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.