+ 2

Why isn't the script displaying text?

I'm trying to review and practice conditional statements. I made an if else statement that will Display a string in a paragraph depending on the conditional value of the variable "hungerLevel". I can get it done easily with document.write but I'm aware this command is only for testing purposes and not actual display of text. Why isn't my code working? Id appreciate the help! <p id="text"></p> <!---- Hunger Script ----> <script> var hungerLevel= prompt("How hungry is Natsuki?") if (hungerLevel<10) { document.getElementById('text').innerHTML("Natsuki isnt hungry."); } else { document.getElementById('text).innerHTML ("Natsuki is hungry! Let's get her some treats!"); } </script> </body>

16th May 2019, 8:21 PM
HeyItsJay
HeyItsJay - avatar
7 Answers
+ 5
https://code.sololearn.com/WHqS4IYSe8Wo/#html <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <p id="text"></p> <!-- Hunger Script --> <script> var hungerLevel= prompt("How hungry is Natsuki?"); var el = document.getElementById('text'); if (hungerLevel<10) { el.innerHTML = "Natsuki isnt hungry."; } else { el.innerHTML = "Natsuki is hungry! Let's get her some treats!"; } </script> </body> </html>
16th May 2019, 8:32 PM
AgentSmith
+ 4
You're welcome bro! Best of luck in your learning.
16th May 2019, 8:36 PM
AgentSmith
+ 4
Look at the code. I corrected some of the mistakes like if you want to compare numbers stored in the prompt variable you need to convert it to number, also missing quotation mark when you get an element 'text' by id and setting the innerHTML. Hope it helps you. https://code.sololearn.com/W1UYauF6ozRG/?ref=app
16th May 2019, 8:37 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 3
Just to explain a little. 1. innerHTML isn't a function, so you're assigning a value to it. In this case, you'll use ###.innerHTML = "whatever" instead of ###.innerHTML("whatever"). 2. Instead of constantly searching for that element, assign it to a variable so it's only having to do that once. Good practice to save on performance. Example: var el = document.getElementById('text'); Then you can just use the variable to reference it instead of always searching for it each time.
16th May 2019, 8:35 PM
AgentSmith
+ 2
HeyItsJay I'm happy to help 😉
16th May 2019, 8:45 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 1
AgentSmith I appreciate the help buddy!
16th May 2019, 8:35 PM
HeyItsJay
HeyItsJay - avatar
+ 1
TheWhiteCat Thank you so much to you as well, I love how well you organized my code it's gonna help me so much to keep this code as reference.
16th May 2019, 8:44 PM
HeyItsJay
HeyItsJay - avatar