Generally it is better not to interfere with the textual content from JavaScript, but if we ever had to capitalize a word, this is a very cool way to do it:
function Capitalize(word)
{
return word.charAt(0).toUpperCase() + word.slice(1);
}
And this is my code in action:
| Code |
//We need to Capitalize the word but we can't modify the HTML
var el = document.getElementById('lblTitle');
el.innerHTML = Capitalize(el.innerHTML);
<div id="lblTitle">france</div>
|
| Preview |
|
france
|
Where would I ever use this function? For instance in places where I can add my own JavaScript (i.e. in external .js file) but I'm unable to modify the HTML itself.
This function can be used together with some sort of ForEach statement to capitalize all words inside a container, for example:
| Code |
//using jQuery to simplify selection
var words = $('#lblSentence').html().split(" ");
var newSentence = '';
for (w in words)
{
words[w] = Capitalize(words[w]);
}
$('#lblSentence').html(words.join(" "));
<div id="lblSentence">the quick brown fox jumps over the lazy dog</div>
|
| Preview |
|
the quick brown fox jumps over the lazy dog
|
Post new comment