简体   繁体   中英

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();

        }
    }

Why 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;
}

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;

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM