Reputation: 1313
I'm trying to capitalize first letter of sentence for every class.
I have html <span class="price"></span>
multiple time on my page and I want to capitalize first letter of every tag. So I have an array of span classes.
Default value of html elements is lowercase, I tried with text-transform:capitalize, it converts first letter of every word.
I tried to write some code but it doesn't work, it goes through loop only once and it doesn't work.
Here is the code, can somebody help me to modify to work
function applySentenceCase() {
var selector = document.getElementsByClassName('price');
for( i =0; i<selector.length; i++) {
var selectorTest = jQuery(selector[i]).text();
return selectorTest.charAt(0).toUpperCase() + selectorTest.substr(1).toLowerCase();
}
}
Upvotes: 3
Views: 15837
Reputation: 463
Your function is basically right. I imagine there is a problem with the jquery? I changed it a tiny bit to use javascript. https://jsfiddle.net/h6h4nswd/
var selectorTest = selector[i].innerHTML;
Upvotes: 1
Reputation: 318162
Why not stick with jQuery, as you're already using it
$('.price').text(function(_, txt) {
return txt.charAt(0).toUpperCase() + txt.slice(1).toLowerCase();
});
Upvotes: 15
Reputation: 137
Iam not sure what you get with your document.getElementsByClassName('price'); but this work it will return Toto
function applySentenceCase()
{
var selector = "toto";
return selector.charAt(0).toUpperCase() + selector.substr(1).toLowerCase();
}
Upvotes: 1
Reputation: 116
You can do it with CSS:
.price:first-letter{
text-transform: capitalize;
}
Upvotes: 1