How do I use this JavaScript variable in HTML?

2020-05-19 04:12发布

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.

8条回答
Lonely孤独者°
2楼-- · 2020-05-19 04:57

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>

查看更多
够拽才男人
3楼-- · 2020-05-19 04:57

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>

查看更多
登录 后发表回答