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.
1 2 3 4 5 6 7 8 9 10 |
$(document).ready(function() { $(":header").each(function(){ html = ''; words = $(this).text().split(' '); $.each(words, function(){ html += '<span style="text-transform: uppercase;">' + this.substring(0,1) + '</span>' + this.substring(1) + ' '; }); $(this).html(html); }); }); |
You can change the elements which are capitalised by adjusting the following line.
1 |
$(":header").each(function(){ |
If you want to capitalise the first letter of each word within a “h1” tag change it to the following.
1 |
$("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.
1 |
$(".title").each(function(){ |