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.
You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.
If you want to display a variable on the screen, this is done with JavaScript.
First, you need somewhere for it to write to:
Then you need to update your JavaScript code to write to that
<p>
tag. Make sure you do so after the page is ready.Try this:
You cannot use js variables inside html. To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html.
You can create an element with an id and then assign that length value to that element.
A good place to start learning how to manipulate pages s the Mozilla Developer Network, they've got a great tutorial about the DOM.
One way you could do it is with
document.write
, which writes html at the end of the currently loaded part of the document - in this case, after the script tag.But it's not a very clean way of doing it. Keep
document.write
for testing purpose because in most cases you can't predict where it will append the content.EDIT: Here, the "clever" way would be to do something like this:
But people are generally lazy and you'll often see
.innerHTML = "something"
instead of a text node.