Why does parseint return Nan?

Asked

Viewed 197 times

2

I’m with 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. Why? If parseint returns it as a numeral ?

3 answers

3


There is no attribute VALUEthen soon the function will not find, look in the console (F12 key) 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 semicolon after the end of each call or variable function.

  • 1

    value exists, but only in the elements that extend from Htmlinputelement and some other elements of <form>

  • 2

    I meant in case the TAG <p> in itself did not possess the attribute VALUE then it does not exist for the elements.

2

Much better you take the amount with textContent instead of innerHTML. This is because if you solve then 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);

Testing:

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);

Testing:

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>

The innerHTML has function to manage HTML code and not to pick text or values in text form.

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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.