Problems with Variables in Jquery | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Problems with Variables in Jquery

Hello, I am starting with jQuery and I have a problem declaring variables. I am making a script to count the number of characters inside an html element, when I make like this, it works: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#demo").text($("#mydiv p").text().length); }); </script> </head> <body> <div id="mydiv"> <p>Hello World!!</p> </div> <p id="demo"></p> </body> </html> However, when I try to put the counting inside of variable, it doesn't work anymore. I tried to make a script like this: <script> var count = $("#mydiv p").text(); $(document).ready(function(){ $("#demo").text(count.length); }); </script> and like this: <script> var count = $("#mydiv p").text().length; $(document).ready(function(){ $("#demo").text; }); </script> And noting works... I believe that is a very silly question, but hopefully somebody can make me understand where it is my mistake. Thanks for the help

18th Jan 2020, 8:29 PM
DevChallenge
3 Answers
+ 1
Kevin E. Torres Caldas : that's not a variable out of scope problem, even if your solution is solving it ;) the problem is that when the count variable is initialized the document isn't yet parsed, so the targeted element (#mydiv p) doesn't exist ^^
18th Jan 2020, 8:48 PM
visph
visph - avatar
+ 1
Yes I know, but the quickest "solution" is to add the variable to the scope, since once the document is loaded the element (#mydiv p) already exists :)
18th Jan 2020, 8:57 PM
Kevin E. Torres Caldas
Kevin E. Torres Caldas - avatar
0
The variable is out of scope, add the variable inside like this: <script> $(document).ready(function() { var count = $("#mydiv p").text(); $("#demo").text(count.length); }); </script>
18th Jan 2020, 8:42 PM
Kevin E. Torres Caldas
Kevin E. Torres Caldas - avatar