Count characters in paragraph using jQuery (*not* for input/textarea)

前端 未结 4 1808
花落未央
花落未央 2021-01-18 00:55

How do I work out in jQuery a character counter of a p/div tag?

Basically i want to show a different css value IF the character value >=50.

Been struggling f

4条回答
  •  别那么骄傲
    2021-01-18 01:36

    Put a "long" class on all div and p elements with more than 50 characters:

    $("p, div").filter(function(){
      return $(this).text().length >=50;
    }).addClass('long');
    

    If you don't know how much content you have, though, then presumably this content is generated dynamically by the server, right? And if this is the case, wouldn't it make more sense to have the server—which knows how much content it's plopping into these containers—add the class dynamically while generating the page to send? Why rely on jQuery?

提交回复
热议问题