Home > OS >  is it possible to access classes inside if statement?? the output what i am getting is wrong
is it possible to access classes inside if statement?? the output what i am getting is wrong

Time:12-02

let count = 0;
let counter = document.querySelector("#number-el");
let btns = document.querySelectorAll(".btn");
let decreaseEl = document.querySelector(".decrease-el");
let increaseEl = document.querySelector(".increase-el");

btns.forEach(function(btn) {
  btn.addEventListener("click", function() {
    if (decreaseEl) {
      count--;
      console.log(count);
    } else if (increaseEl) {
      count  ;
    } else {
      count = 0;
    }
    if (count < 0) {
      counter.style.color = "green";
    }
    if (count > 0) {
      counter.style.color = "red";
    }
    if (count === 0) {
      counter.style.color = "yellow";
    }
    counter.textContent = count;
  });
});
<div >
  <div>
    <p id="counter-el">COUNTER
      <div id="number-el">0</div>
    </p>
    <button >INCREASE</button>
    <button >RESET</button>
    <button >DECREASE</button>
  </div>
</div>

It's a program to perform a counter which increases, decreases, and reset the count from 0, but the output that I am getting is only increasing with a negative sign

i access classes inside if statement directly. is it possible to directly access classes without using event objects.

CodePudding user response:

Added values in button and used switch/case

let count = 0;
let counter = document.querySelector("#number-el");
let btns = document.querySelectorAll(".btn");
let decreaseEl = document.querySelector(".decrease-el");
let increaseEl = document.querySelector(".increase-el");

btns.forEach(function(btn) {
  btn.addEventListener("click", function(e) {
    switch (e.target.value) {
      case "INCREASE":
        count  ;
        break;
      case "DECREASE":
        count--;
        break;
      case "RESET":
        count = 0;
        break;
      default:
        break;
    }
    if (count < 0) {
      counter.style.color = "green";
    }
    if (count > 0) {
      counter.style.color = "red";
    }
    if (count === 0) {
      counter.style.color = "yellow";
    }
    counter.textContent = count;
  });
});
<div >
  <div>
    <p id="counter-el">COUNTER
      <div id="number-el">0</div>
    </p>
    <button  value="INCREASE">INCREASE</button>
    <button  value="RESET">RESET</button>
    <button  value="DECREASE">DECREASE</button>
  </div>
</div>

CodePudding user response:

Change

btn.addEventListener("click", function () {
    if (decreaseEl) { ... }

into

btn.addEventListener("click", function (ev) {
    if (ev.target.closest(".btn") == decreaseEl) { ... }

as otherwise the if will always be fulfilled (true). ev.target.closest(".btn") == decreaseEl will check, whether you have clicked on the decreaseEl DOM element or on any of its children.

  • Related