最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Capitalize first letter using javascript - Stack Overflow

programmeradmin2浏览0评论

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
Add a comment  | 

4 Answers 4

Reset to default 15

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

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;
发布评论

评论列表(0)

  1. 暂无评论