How to count the number of characters in a DIV with javascript

后端 未结 4 1379
鱼传尺愫
鱼传尺愫 2021-01-03 22:31

Hi I want to be able to count the number of displayed characters in a Div with javascript/jquery. For example

This is my div!&l

相关标签:
4条回答
  • 2021-01-03 23:06

    Try this. I am trimming to avoid any white spaces in the content start or end.

    $.trim($("#mydiv").text()).length
    

    If you want to keep spaces also in the count then don't trim it just use this.

    $("#mydiv").text().length
    
    0 讨论(0)
  • 2021-01-03 23:07

    In case you are searching for a Vanilla Javascript solution.

    Here is one with whitespace:

    document.querySelectorAll('#mydiv')[0].textContent.length
    

    Here is one without whitespace:

    document.querySelectorAll('#mydiv')[0].textContent.replace(/\s/g,'').length
    
    0 讨论(0)
  • 2021-01-03 23:10

    Sample
    http://jsfiddle.net/TrMRB/

    $("#mydiv p").text().length; 
    
    0 讨论(0)
  • 2021-01-03 23:21
    $('#mydiv').text().length
    

    should do the trick.

    0 讨论(0)
提交回复
热议问题