Search code examples
javascripthtmleventsparseint

Adding numbers in span JavaScript


I have a button on my page with click counter as span (with class .counter). Once the button is clicked, +1 should be added to the counter (on page, not in console). How can I add 1 to the string in span, currently innerHTML is 0? I tried with the code below but it doesn't work, unfortunately. When I tried without parseInt, digits were added to a span so I got e.g. 011 instead of 2.

document.addEventListener("DOMContentLoaded", function () {
    var counters = document.querySelectorAll(".counter");

    var btn1 = document.getElementById("button1");

    function btn1Count (event) {
         parseInt(counters[0].innerHTML,10) += 1;
     }

    btn1.addEventListener("click", btn1Count);

});

Solution

  • Use parseInt but like :

    counters[0].innerHTML = parseInt(counters[0].innerHTML,10) + 1;
    

    NOTE : It'll be better to use textContent instead if you would just to append text (No html) :

    counters[0].textContent = parseInt(counters[0].textContent,10) + 1;
    

    Hope this helps.

    var btn1 = document.getElementById("button1");
    var counters = document.querySelectorAll(".counter");
    
    btn1.addEventListener("click", btn1Count);
    
    function btn1Count (event) {
      counters[0].textContent = parseInt(counters[0].textContent) + 1;
    }
    <button id="button1">Button 1</button>
    <br>
    <span class='counter'>0</span>