John Smith John Smith - 1 year ago 63
Javascript Question

What is the correct way to use JavaScript to perform arithmetic on a DOM object?

I've been trying to use the following code to add 1 from the value within the paragraph tags, but only get NaN as the output value:

<p id="myNumber">5</p>
<button onclick="increment()">Click</button>

function increment() {
document.getElementById("myNumber").innerHTML = document.getElementById("myNumber").value + 1;

Can anyone say why this is outputting NaN?

Answer Source

It is NaN because the .value of the <p> element is undefined. As a result you are doing this:

undefined + 1

Which is NaN. Get the value from the element using .textContent or .innerHTML depending on the structure, then use parseInt.

function increment() {
    document.getElementById("myNumber").textContent = parseInt(document.getElementById("myNumber").textContent,10) + 1;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download