0

Through js, I have been retrieving the ids of buttons on an html page and passing them through a function that changes a string. The function contains an if statement that should cancel when certain buttons are clicked but the function never stops.

This is my code:

let buttons = document.querySelectorAll("button")
buttons.forEach(function(btn) {
    btn.addEventListener('click', () => {
        if (btn.getAttribute('id') != "reset" || btn.getAttribute('id') != "equals") {
            //Do something
        }
    })
})

The problem is, even when the id of the btn == "#reset" or "#equals" the function still goes through. I know the reception of the id is working because I tested what happened when I clicked by logging the button id in js.

This code worked, but is repetitive and doesn't make use of the or operator:

let buttons = document.querySelectorAll("button")
buttons.forEach(function(btn) {
    btn.addEventListener('click', () => {
        if (btn.getAttribute('id') != "reset") {
            if (btn.getAttribute('id') != "equals") {
            console.log(btn.getAttribute('id'))
            document.getElementById("content").textContent += btn.textContent
    }
}})
})

I expect the function to not go through when the id has a value of reset or equals. I know the problem is somewhere in the if statement but I can't figure it out.

Tom Dufall
  • 871
  • 1
  • 10
  • 21

1 Answers1

1

Problem is OR operator. You should use AND Operator instead. Say when btn "reset" is clicked, the first condition returns false but second condition evaluates true and thus if statement executes.