0
<button onclick="nums()">Input</button>
<p id="number">5</p>
<p id="aNumber"></p>

<script>
function nums() {
  var x = parseInt(document.getElementById("number").value);
  var y = parseInt(1);
  var z = x + y;
  document.getElementById("aNumber").innerHTML = z;
}
</script>

</body>

I can't understand why this does not work. What do I need to do to get p with id number to go into a function and turn into an int?

4 Answers4

3

An element has a value if it's in input element or something like that, here, you have the content of your p tag.

This will work:

parseInt(document.getElementById("number").innerText);

Btw, you don't need the parseInt to define y:

var y = 1;
Axnyff
  • 9,213
  • 4
  • 33
  • 37
0

You should use

document.getElementById("number").innerText

value is only for input elements, not for normal HTML entities.

mousetail
  • 7,009
  • 4
  • 25
  • 45
0

or use textContent, but it's will return string

function nums() {
  var x = document.getElementById("number").textContent;
  x = parseInt(Number(x))
  var y = 1;
  var z = x + y;
  document.getElementById("aNumber").innerHTML = z;
}
<button onclick="nums()">Input</button>
<p id="number">5</p>
<p id="aNumber"></p>
0

The text within the <p> tag, is not retrieved by .value.

You should retrieve with something like the following:

var x = parseInt(document.getElementById("number").innerText);
rleiva93
  • 216
  • 1
  • 4