Joanna
Joanna

Reputation: 289

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);

});

Upvotes: 2

Views: 1806

Answers (2)

crackpotHouseplant
crackpotHouseplant

Reputation: 401

Just change

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

you just didn't set the span content

Upvotes: 1

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

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>

Upvotes: 3

Related Questions