snoopy_15
snoopy_15

Reputation: 1313

Capitalize first letter using javascript

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

Answers (4)

Observer
Observer

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

adeneo
adeneo

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

Alex C
Alex C

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

Lucas Ten&#243;rio
Lucas Ten&#243;rio

Reputation: 116

You can do it with CSS:

.price:first-letter{
   text-transform: capitalize;
}

Upvotes: 1

Related Questions