11

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

4 Answers 4

30

$("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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

change the length() to length
6

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);
});

Comments

2

try this:

$(document).ready(function(){
  var count = $('h1').text().length;
  alert(count);
})

Comments

-2
<script type="text/javascript">
 var count = $('h1').html().length;
 alert(count);

</script>

$('h1') is object, so the length is 0 (the first one, or the only one)

you need to .html() to get whats inside, then check length

1 Comment

"$('h1') is object, so the length is 0" is wrong. It's 0 because it has not loaded yet. $('h1').length will return the number of h1 elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.