jQuery count characters and add class

后端 未结 4 1565
予麋鹿
予麋鹿 2021-01-07 04:02

Is it possible to use jQuery to count how many characters are in, for example, an

  • , and if the amount is greater than XX characters, apply a class to
  • 相关标签:
    4条回答
    • 2021-01-07 04:08

      You could do something like this:

      // The number of characters
      var XX = 100;
      
      $('li').filter(function() {
          return $(this).text().length > XX;
      }).addClass('someClass');
      
      0 讨论(0)
    • 2021-01-07 04:26

      Why not select your <li> element into a variable and get its length?

      var length = $('li').html().length;
      

      From here, just check if the value on length is greater than the value you're comparing to and use .addClass()

      0 讨论(0)
    • 2021-01-07 04:34

      You can get the amount of characters in a string by doing this a.length, where a is a string.

      $('a').each(function(){
       if($(this).text().length > XX){
        $(this).addClass('someClass');
       }
      });
      
      0 讨论(0)
    • 2021-01-07 04:35

      If you want to target a specific li item (instead of all li elements in your page) you can give it an ID :

      <li id="myli">...</li>
      

      Then if you want to execute your code at page load do something like this :

      $(document).ready(function() {
          var yourElement = $('#myli');
          var charLength = yourElement.text().length;
          if(charLength > xx){
             yourElement.addClass('yourClass');
          }
      });
      
      0 讨论(0)
    提交回复
    热议问题