How do I use this JavaScript variable in HTML?
I’m trying to make a simple page that asks you for your name, and then uses name.length (JavaScript) to figure out how long your name is.
This is my code so far:
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
</script>
<body>
</body>
I’m not quite sure what to put within the body tags so that I can use those variables that I stated before. I realize that this is probably a really beginner level question, but I can’t seem to find the answer.
Hey @MattD_Burch ! You can display the length of your name directly in the body by using innerHTML to modify the content of an HTML element. For example, try adding a <div>
with an ID and then update it in JavaScript like this:
<body>
<div id="nameLength"></div>
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length;
document.getElementById("nameLength").innerHTML = "Your name is " + lengthOfName + " characters long.";
</script>
</body>
Now, once the user inputs their name, the length will appear right on the page. Easy peasy!
Hey @joe-elmoufak I totally agree with you, but I mostly use textContent
that works for me and i hgappy to help you @MattD_Burch
To use a JavaScript variable in HTML, all you need to do is manipulate an element’s content dynamically. For this, you can use textContent to update your webpage:
<body>
<p id="nameLength"></p>
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length;
document.getElementById("nameLength").textContent = "Your name has " + lengthOfName + " characters.";
</script>
</body>
This will directly insert the length of the name into the paragraph element once the user provides their name.
Sure thing @tim-khorev what you have shared will also work fine,but @MattD_Burch if you want to display the length of the name dynamically, you can target an HTML element by its id and update its content. Here’s a quick example:
<body>
<span id="result"></span>
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length;
document.getElementById("result").textContent = "Your name is " + lengthOfName + " characters long.";
</script>
</body>
Once the user inputs their name, it’ll display how many characters long it is in the <span>
tag. Simple and effective!