Search code examples
javascripthtmldomweb-frontend

is there any method in javascript to operate a function singly for one HTML element?


I have three box in my web page , each box includes a + button , a - button and a span with pre-assigned value as 0. I want when I click on + or - button, the value of span get one more or less according to times of clicking + or -. but my code doesnt work well. what should I do ? Thanks.

<div class="box">
    <button class="minus-btn" type="button">-</button>
    <span class="display-num">0</span>
    <button class="plus-btn" type="button">+</button>
</div>
<div class="box">
    <button class="minus-btn" type="button">-</button>
    <span class="display-num">0</span>
    <button class="plus-btn" type="button">+</button>
</div>
<div class="box">
    <button class="minus-btn" type="button">-</button>
    <span class="display-num">0</span>
    <button class="plus-btn" type="button">+</button>
</div>

function $(query) {
    return document.querySelector(query);
}
function $All(query) {
    return document.querySelectorAll(query);
}
const box = $All('.box');
const plusBtn = $All('.plus-btn');
const minusBtn = $All('.minus-btn');
const displayNum = $All('.display-num');

box.forEach((e) => {
    e.addEventListener('click', (el) => {
        if (el.target.classList.contains('plus-btn')) {
            let num = 0;
            displayNum.forEach((e) => {
                e.innerHTML = num++;
            })
        } else if (el.target.classList.contains('minus-btn')) {
            let num = 0;
            displayNum.forEach((e) => {
                e.innerHTML = num--;
            })
        }
    }, false)
})

Solution

  • It is probably easier to react on the actual button being pressed, rather than checking the boxes etc, try the following:

    plusBtn.forEach((e, idx) => {
      e.addEventListener(
        'click',
        (el) => {
          calcIt(displayNum[idx], 1);
        },
        false
      );
    });
    
    minusBtn.forEach((e, idx) => {
      e.addEventListener(
        'click',
        (el) => {
          calcIt(displayNum[idx], -1);
        },
        false
      );
    });
    
    function calcIt(element, value) {
      var num = element.innerHTML;
      element.innerHTML = (+num) + value;
    }
    

    Remove the block:

    box.forEach((e) => {
        e.addEventListener('click', (el) => {
            if (el.target.classList.contains('plus-btn')) {
                let num = 0;
                displayNum.forEach((e) => {
                    e.innerHTML = num++;
                })
            } else if (el.target.classList.contains('minus-btn')) {
                let num = 0;
                displayNum.forEach((e) => {
                    e.innerHTML = num--;
                })
            }
        }, false)
    })
    

    Stackblitz: https://jquery-rfrzsp.stackblitz.io

    (https://stackblitz.com/edit/jquery-rfrzsp)