How to change number in an element

Issue

So I have an element with a ‘&nbsp’ in it. I’m trying to increment the number by 1 whenever a button on the page is clicked. I’ve been trying but keep getting not a number (NaN) output.

    var counter = parseInt(document.getElementById("itemCounter").innerText);
    const AddToCart = Array.from(document.getElementsByClassName("AddToCart"));
    
    AddToCart.forEach(btn => {
        btn.addEventListener("click", function () {
            counter = counter+1;
            document.getElementById("itemCounter").innerText = parseInt(counter)
        })
    });

Here’s what I tried could someone please point out my mistake?
Thanks

Solution

parseInt when it is not a number will return NaN. So you can add an or to set it to zero when it runs into this state.

var counter = parseInt(document.getElementById("itemCounter").innerText) || 0;
const AddToCart = Array.from(document.getElementsByClassName("AddToCart"));

AddToCart.forEach(btn => {
  btn.addEventListener("click", function() {
    counter = counter + 1;
    document.getElementById("itemCounter").innerText = counter
  })
});
<div id="itemCounter">&nbsp;</div>

<button class="AddToCart">Foo 1</button>
<button class="AddToCart">Foo 2</button>
<button class="AddToCart">Foo 3</button>

Answered By – epascarello

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.