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

javascript - Counting Characters Inside a Paragraph - Stack Overflow

programmeradmin0浏览0评论

How do you count how many characters are in a paragraph tag with jQuery/Javascript? For example in this sample it would be 3.

<div>
 <p class="tag">Jam</p>
</div>

Are you able to select the characters with .length() somehow?

How do you count how many characters are in a paragraph tag with jQuery/Javascript? For example in this sample it would be 3.

<div>
 <p class="tag">Jam</p>
</div>

Are you able to select the characters with .length() somehow?

Share Improve this question asked Dec 31, 2015 at 7:50 James IvesJames Ives 3,3654 gold badges34 silver badges69 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

This is what you want

$.trim($("p").text()).length;

This can be done pretty easily with vanilla javascript :

var text = document.querySelector('.tag').innerText;
var textLength = text.trim().length;
// textLength = 3

And, if you have your own website editor like me, you can limit the number of characters very fast and pact using this algorithm:

JS:

function max_generic(event, elementId, max_gen_number){
//event = event.keyCode
//elementId = id for element
//max_gen_number = max number of characters
var keycode = (event.which) ? event.which : event.keyCode;
if(keycode !== 8){
var text_new = null;
var myDiv = document.getElementById(elementId).innerText;
var newlength = max_gen_number;
myDiv = document.getElementById(elementId).innerText.length;
if(myDiv == newlength){
text_initial_gen = document.getElementById(elementId).innerText;
document.getElementById(elementId).innerText = text_initial_gen;
}
if(myDiv >= newlength){
setTimeout(function(){document.getElementById(elementId).innerHTML = text_initial_gen}, 100);
} else{}

} else{}

}

HTML:

<p id="this_id_does_not_matter" onkeydown="max_generic(event, this.id, 10)">HELLO</p>

So easy, no ? :)

And, you can get the length of text paragraph or h1,h2,h3,h4 elements, etc., doesn't matter with:

JS:

document.getElementById("this_id_does_not_matter").innerText.length;

Or you can go to create a function like this:

function get_text_length(id)
{
return document.getElementById(id).innerText.length;
}

And then, you can customize this function to your liking.

Alexie follow on github :)

发布评论

评论列表(0)

  1. 暂无评论