I've been stuck trying to figure this out for hours. What on earth is going wrong? If I understand correctly, the value you get from getElementById is a string, so what I'm trying is to parse it into an int (in order to use it for sums), but when I try to print it as an int, it tells me NaN.
The expected result is to print the value 123 back in the test div, replacing the text Click, but instead it only prints NaN.
<div id="test" value="123" onclick="testFunction()">Click</div>
function testFunction() {
var strVal = document.getElementById('test').value;
var intVal = parseInt(strVal);
document.getElementById('test').innerHTML = intVal;
}
There's no inherent value
property for div
. You'll need to access the attribute directly:
function testFunction() {
var strVal = document.getElementById('test').getAttribute('value')
var intVal = parseInt(strVal);
document.getElementById('test').innerHTML = intVal;
}
<div id="test" value="123" onclick="testFunction()">Click</div>