25

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.

Arun Bertil
  • 4,360
  • 3
  • 29
  • 57
Joseph
  • 400
  • 1
  • 3
  • 8

8 Answers8

62

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:

<body>
    <p id="output"></p>
</body>

Then you need to update your JavaScript code to write to that <p> tag. Make sure you do so after the page is ready.

<script>
window.onload = function(){
    var name = prompt("What's your name?");
    var lengthOfName = name.length

    document.getElementById('output').innerHTML = lengthOfName;
};
</script>

window.onload = function() {
  var name = prompt("What's your name?");
  var lengthOfName = name.length

  document.getElementById('output').innerHTML = lengthOfName;
};
<p id="output"></p>
Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
  • 2
    Thanks! So I would put the script after the body tags? – Joseph May 04 '15 at 21:37
  • 1
    @Joseph: Script tags normally go in the ``. `window.onload` binds an event so that the code won't run until the page is loaded. – Rocket Hazmat May 04 '15 at 21:42
  • 2
    Okay, thanks! Best answer :) But if I were to remove that window.onload and put it in the beginning, would that change anything? – Joseph May 04 '15 at 21:49
  • 2
    @Joseph: That would change *everything*! When the browser loads your page, it starts from the top down. So, if you remove `window.onload`, then it would try to write to the `

    ` tag before it exists. You *could* remove the `window.onload`, if and only if you put the script tag after the `

    `. I prefer to keep my scripts in the ``.
    – Rocket Hazmat May 04 '15 at 21:56
  • I see. Thanks for the explanation and help! :) – Joseph May 04 '15 at 22:25
  • mind to run script innerHTML part after all html loads! – Sebastian Juarez Apr 13 '20 at 02:55
9

You can create a <p> element:

<!DOCTYPE html>
<html>
  <script>
  var name = prompt("What's your name?");
  var lengthOfName = name.length
  p = document.createElement("p");
  p.innerHTML = "Your name is "+lengthOfName+" characters long.";
  document.body.appendChild(p);
  </script>
  <body>
  </body>
  </html>
user1823
  • 1,041
  • 6
  • 18
  • 1
    Thanks. The code snippet runner within StackOverflow seems like it works. I'm wondering how that works; I was thinking about writing it so that it was like "Your name is x characters long". – Joseph May 04 '15 at 17:26
  • I can fix that for you easily. This works by creating a paragraph element within the javascript, adding the text, and adding the element to the page. – user1823 May 04 '15 at 17:34
  • 1
    So how would I do that? – Joseph May 04 '15 at 21:35
7

You can create an element with an id and then assign that length value to that element.

var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('message').innerHTML = lengthOfName;
<p id='message'></p>
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
imran qasim
  • 1,030
  • 12
  • 16
  • 2
    `.value` won't exist on a `

    `, only `input`. PS I'm not the downvoter, this answer is easily fixed and then is a correct answer.

    – Tom May 04 '15 at 17:17
1

Try this:

<body>
    <div id="divMsg"></div>
</body>
<script>
    var name = prompt("What's your name?");
    var lengthOfName = name.length;
    document.getElementById("divMsg").innerHTML = "Length: " + lengthOfName;
</script>
Márcio Gonzalez
  • 982
  • 6
  • 19
1
<head>
    <title>Test</title>
</head>

<body>
    <h1>Hi there<span id="username"></span>!</h1>
    <script>
       let userName = prompt("What is your name?");
       document.getElementById('username').innerHTML = userName;
    </script>
</body>
Nico
  • 21
  • 1
0

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.

Kalyan Kumar S
  • 194
  • 1
  • 1
  • 8
0

The HTML tags that you want to edit is called the DOM (Document object manipulate), you can edit the DOM with many functions in the document global object.

The best example that would work on almost any browser is the document.getElementById, it's search for html tag with that id set as an attribute.

There is another option which is easier but works only on modern browsers (IE8+), the querySelector function, it's will find the first element with the matched selector (CSS selectors).

Examples for both options:

<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
</script>
<body>
  <p id="a"></p>
  <p id="b"></p>
  <script>
    document.getElementById('a').innerHTML = name;
document.querySelector('#b').innerHTML = name.length;</script>
</body>
InvisibleUn1corn
  • 579
  • 1
  • 8
  • 21
-2

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.

<script>
  var name = prompt("What's your name?");
  document.write("<p>" + name.length + "</p>");
</script>

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:

<script type="text/javascript">
  window.addEventListener("load", function(e) {
    var name = prompt("What's your name?") || "";
    var text = document.createTextNode(name.length);
    document.getElementById("nameLength").appendChild(text);
  });
</script>
<p id="nameLength"></p>

But people are generally lazy and you'll often see .innerHTML = "something" instead of a text node.

Domino
  • 4,988
  • 27
  • 51
  • 2
    I wouldn't actually suggest using `document.write`. You should be using `.innerHTML` (or `.appendChild`). I guess it's ok if the script is running *before* the page is fully loaded, but once the page is fully loaded, `document.write` will erase the whole page. – Rocket Hazmat May 04 '15 at 17:20
  • [More reasons not to use document.write](http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) – Tom May 04 '15 at 17:22
  • @RocketHazmat Agreed. I added a mention about only using it for testing purpose. – Domino May 04 '15 at 17:24
  • @Tom That link pretty much confirms my thoughts, innerHTML is almost as bad as document.write. – Domino May 04 '15 at 17:25