skip to Main Content

I’m trying to build a javascript counter, but my code bugged:

let counterDisplayElem = document.querySelector('.counter-display');
let counterMinusElem = document.querySelector('.counter-minus');
let counterPlusElem = document.querySelector('.counter-plus');

let count = 0;

updateDisplay();

counterPlusElem.addEventListener("click", () => {
  count++;
  updateDisplay();
});

counterMinusElem.addEventListener("click", () => {
  count--;
  updateDisplay();
});

function updateDisplay() {
  counterDisplayElem.innerHTML = count;
}
<h1 class="counterdisplay">(..)</h1>
<button class="counter-minus">-</button>
<button class="counter-plus">+</button>

I looked online but I didn’t find an answer…

2

Answers


  1. The class name doesn’t match between on h1 tag and your js code.

    Fix:
    Change

    <h1 class="counterdisplay">(..)</h1>
    

    to

    <h1 class="counter-display">(..)</h1>
    
    Login or Signup to reply.
  2. Your classes name don’t match:

    You should have this:

    <h1 class="counter-display">
    

    But instead of this, so change it:

    <h1 class="counterdisplay">
    

    And also, even though it won’t affect your js code in this case, it is ALWAYS a good practice to put a semi-colon ; at the end of every js line/function

    Hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search