开发者

Count characters in H1 tag

开发者 https://www.devze.com 2023-02-18 22:32 出处:网络
I need to count the number of characters rendered in an H1 tag. Is there any way to do this. I know there are a lot of character counters but they seem to be built for inputs/textareas. Many thanks in

I need to count the number of characters rendered in an H1 tag. Is there any way to do this. I know there are a lot of character counters but they seem to be built for inputs/textareas. Many thanks in adv开发者_JAVA技巧ance.

C


Like this:

alert("Text length: "+$("h1").text().length);

Not counting whitespace:

alert("Text length: "+$("h1").text().replace(" ", "").length);


This can also be accomplished by passing a function into the .text() method in jQuery.

$("h1").text(function(index, text){
    alert(text.length);
});

note, this will run for every <h1/> on your page.

Code example on jsfiddle.


try this:

var length = $("h1").html().length;
alert(length);


if this tag has a class (in this case h1class) then you might be able to use something like:

alert($(".h1class").text().length);

you could also use it directly but that might get you in trouble if there are more than one h1 tag


I may not be understanding your question right, so forgive me if i give you a wrong answer, but i think what you want to do is get the text out of the tag first

$('h1').text().length

or if you want to count the inside tag as well you can do

$('h1').html().toString().length


Made what you want with

<h1>oi oi oi </h1>

and

console.log($('h1').contents()[0].length);

If you're H1 had an ID it would probably be better

0

精彩评论

暂无评论...
验证码 换一张
取 消