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.