kevinkt kevinkt - 3 months ago 10
Javascript Question

Getting a number value from getElementById not working

I have a simple function that is supposed to decrease the number inside a span of id "numactions" every time a button is clicked. What I'm missing is how to grab the value of the span id. I'm trying getElementById but that doesn't work.

<span id="numactions">5</span>

<button type="button" onClick="clickME()">Click me</button>

<script>
var clicks = document.getElementById("numactions");

function clickME() {
clicks -= 1;
document.getElementById("numactions").innerHTML = clicks;
}
</script>

Answer

Your code has two issues.. first, this line:

var clicks = document.getElementById("numactions");

will grab the HTML element span not the 5, to get the content you should use .textContent or .innerHTML.

Second, using the above you'll get a "string" representation of the content, not a "number", so you'll need to use parseInt() (1) to get a numeric value.

codePen

var clicks = parseInt(document.getElementById("numactions").textContent, 10);

function clickME() {
  clicks -= 1;
  document.getElementById("numactions").innerHTML = clicks;
}
<span id="numactions">5</span>

<button type="button" onClick="clickME()">Click me</button>


(1) It's highly recommended to use radix, the ,10) part of the parseInt in the answer, which here means decimal numeral system. Also, while using parseInt() you get integers, for float you should use parseFloat() instead.

Comments