Why does parseInt return NaN?

2

I have this code:

function aparecer() {
  const elemento1 = document.getElementById('numero').value;
  const elemento2 = parseInt(elemento1);

  alert(elemento2)
}
<html>

<body>
  <button onClick="aparecer()"> Aparecer </button>
  <button onClick="desaparecer()"> Desaparecer </button>
  <p id="numero">0 </p>
</body>

</html>

But it is returning NaN. Because? If parseInt returns it as a numeral?

    
asked by anonymous 18.02.2018 / 19:07

3 answers

3

There is no attribute VALUE so soon the function will not find, look at the console (Key F12) to see the error that causes.

Replace with innerHTML :

function aparecer() {
  const elemento1 = document.getElementById('numero').innerHTML;
  const elemento2 = parseInt(elemento1);

  alert(elemento2);
}

Always use a semicolon after the end of each calling function or variable.

    
18.02.2018 / 19:33
2

You'd better get the value with textContent instead of innerHTML . This is because if you later resolve to add some other tag in the element's HTML, it will again return NaN .

Examples with innerHTML :

 ✓ OK! IRÁ RETORNAR 0
<p id="numero">0</p>
parseInt(document.getElementById('numero').innerHTML);

 X ERRO! IRÁ RETORNAR NaN
<p id="numero"><b>0</b></p>
parseInt(document.getElementById('numero').innerHTML);

Test:

function aparecer() {
  const elemento1 = document.getElementById('numero').innerHTML;
  const elemento2 = parseInt(elemento1);

  alert(elemento2)
}
<button onClick="aparecer()"> Aparecer </button>
<button onClick="desaparecer()"> Desaparecer </button>
<p id="numero"><b>0</b> </p>

Examples with textContent :

 ✓ OK! IRÁ RETORNAR 0
<p id="numero">0</p>
parseInt(document.getElementById('numero').textContent);

 ✓ OK! IRÁ RETORNAR 0
<p id="numero"><b>0</b></p>
parseInt(document.getElementById('numero').textContent);

Test:

function aparecer() {
  const elemento1 = document.getElementById('numero').textContent;
  const elemento2 = parseInt(elemento1);

  alert(elemento2)
}
<button onClick="aparecer()"> Aparecer </button>
<button onClick="desaparecer()"> Desaparecer </button>
<p id="numero"><b>0</b> </p>

innerHTML has the function of managing HTML code and not to get text or values in text form.

    
18.02.2018 / 22:19
0

function aparecer() {
  var elemento1 = document.getElementById("numero").getAttribute("value");
  var elemento2 = parseInt(elemento1);

  alert(elemento2);
}
<html>

<body>
  <button onClick="aparecer()"> Aparecer </button>
  <button onClick="desaparecer()"> Desaparecer </button>
  <p id="numero" value="0">0</p>
</body>

</html>
    
18.02.2018 / 19:17