JQuery Account Symbols

I am having trouble figuring out why a jquery line 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 get 0

+6
source share
4 answers

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

What would you like:

 $(document).ready(function() { var count = $("h1").text().length; alert(count); }); 
+15
source

You get 0 because h1 did not load when the code was run, so first you need to put it in document.ready. It still won’t give the answer you need as it will just tell you the number of h1 tags on the page. To get the answer you need, follow these steps:

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

try the following:

 $(document).ready(function(){ var count = $('h1').text().length; alert(count); }) 
+2
source
 <script type="text/javascript"> var count = $('h1').html().length; alert(count); </script> 

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

you need .html() to get inside and then check the length

-2
source

Source: https://habr.com/ru/post/906858/


All Articles