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();
}
}
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();
}
}
Share
Improve this question
asked Mar 3, 2016 at 20:50
snoopy_15snoopy_15
1,3234 gold badges18 silver badges31 bronze badges
1
- 1 You sure are replacing the characters, but where exactly do you think you're returning the string ? – adeneo Commented Mar 3, 2016 at 21:00
4 Answers
Reset to default 15Why not stick with jQuery, as you're already using it
$('.price').text(function(_, txt) {
return txt.charAt(0).toUpperCase() + txt.slice(1).toLowerCase();
});
You can do it with CSS:
.price:first-letter{
text-transform: capitalize;
}
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();
}
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;