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?
3 Answers
Reset to default 7This 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 :)