Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery count characters

Tags:

jquery

I'm having problems to figure out why jquery string counter won't show me the expected result.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
 var count = $('h1').length;
 alert(count);

</script>

</head>
<body>

<h1>some text</h1>

</body>
</html>

the result should be with this example 9, but instead I'm getting 0

like image 344
lgt Avatar asked Jan 25 '12 14:01

lgt


2 Answers

$("h1") returns a jQuery object (in which the length property is the number of elements returned), and since you are calling it before the page is completely loaded it is actually retuning 0 elements.

What you want is:

$(document).ready(function() {
    var count = $("h1").text().length;
    alert(count);
});
like image 135
Matt MacLean Avatar answered Nov 20 '22 06:11

Matt MacLean


You are getting 0 because the h1 hasnt loaded when the code has been run so firstly you need to put it inside a document.ready. This still won't give the answer you want as it will just tell you the number of h1 tags on the page. To get the answer you want you need to do:

$(document).ready(function() {
    var count = $('h1').text().length;
    alert(count);
});
like image 6
Richard Dalton Avatar answered Nov 20 '22 06:11

Richard Dalton