Search code examples
javascriptaddeventlistener

How can I create a button that increments a counter when clicked?


I am trying to make a button that increments a counter's value by 1 when clicked. My code, however, doesn't seem to work.

var count = 1;
var button = document.querySelector("#increment");

button.addEventListener("click", function() {
  var increment = document.getElementById("#count");
  increment.value = count;
  count++;
});
<h4>Current count: <span id="count">0</span></h4>
<div class="container">
  <button id="decrement">Decrement</button>
  <button id="increment">Increment</button>
</div>


Solution

  • You don't need # in getElementById and use innerHTML to set value. Don't use querySelector when you can get by id.

    Like this:

    let count = 0;
    const button = document.getElementById("increment");
    const button2 = document.getElementById("decrement");
    const textHolder = document.getElementById("count");
    textHolder.innerHTML = count;
    
    button.addEventListener("click", function() {
      textHolder.innerHTML = ++count;
    });
    
    button2.addEventListener("click", function() {
      textHolder.innerHTML = --count;
    });
    <h4>Current count: <span id="count">0</span></h4>
    <div class="container">
      <button id="decrement">Decrement</button>
      <button id="increment">Increment</button>
    </div>