-1

I am trying to practice JavaScript and I wanted to output the variable in a created element. But the value stored in the variable is not output. Only the word answer. I console logged the variable and it has a number value in it. But it does not display only the word I do not know why?

var name, computer, age, answer;

name = window.prompt("What is your name?");
alert("you chose " + name);

computer = window.prompt("How old where you when you used a computer");
alert(computer + "  0.0");

age = window.prompt("How old are you now?");
alert("you are " + age);

if (age - computer < 0) {
  age = 0;
  computer = 0;
}

answer = age - computer;

var con = document.getElementById('container');
var h1 = document.createElement('h1');
var h1Text = document.createTextNode('answer');
h1.appendChild('h1Text');
con.appendChild('h1');

// document.write(age + " - " + computer + " = ");
// document.write(answer + "<br>");
body {
  background-color: orange;
}

div {
  background-color: green;
  max-width: 960px;
  margin: 3em auto;
}
<div id="container"></div>

3
  • instead of creating a text node, can't you edit the innerText property of the h1 tag? Commented Jan 20, 2018 at 18:05
  • I suggest you look at the JavaScript console. Your script causes an error. You should start there in figuring out how to fix your program. Commented Jan 20, 2018 at 18:09
  • var h1Text = document.createTextNode('answer'); h1.appendChild('h1Text'); con.appendChild('h1'); -> var h1Text = document.createTextNode(answer); h1.appendChild(h1Text); con.appendChild(h1); Commented Jan 20, 2018 at 18:09

2 Answers 2

2

You are passing the string answer instead of the variable answer to createTextNode and hence answer text is being displayed, also h1 and h1Text needs to be variable in

h1.appendChild(h1Text);
con.appendChild(h1);

Working snippet

var name, computer, age, answer;

name = window.prompt("What is your name?");
alert("you chose " + name);

computer = window.prompt("How old where you when you used a computer");
alert(computer + "  0.0");

age = window.prompt("How old are you now?");
alert("you are " + age);

if (age - computer < 0) {
  age = 0;
  computer = 0;
}

answer = age - computer;

var con = document.getElementById('container');
var h1 = document.createElement('h1');
var h1Text = document.createTextNode(answer);
h1.appendChild(h1Text);
con.appendChild(h1);

// document.write(age + " - " + computer + " = ");
// document.write(answer + "<br>");
body {
  background-color: orange;
}

div {
  background-color: green;
  max-width: 960px;
  margin: 3em auto;
}
<div id="container"></div>

Sign up to request clarification or add additional context in comments.

Comments

-1

It is because you are not assigning the variable answer to anything.

Try

h1Text.innerHTML = answer;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.