I have three buttons. All i need is to add into array a corresponding value by the clicking on the button but if the value already exists in my array, I need to remove it from my array. My code works only if we use it twice (add and delete) the same button. But if we use it with differents - it brokes. Try it with example below. What is the reason to that behavior ?
Only pure JavaScript.
let buttons = document.querySelectorAll('.string')
let array = []
let value = ''
buttons.forEach(el => el.addEventListener('click', () => {
value = el.innerHTML
for (i = 0; array.length + 1; i++) {
if (array[i] === value) {
delete array[i]
array = array.filter(x => x) // clear empty values
console.log('deleted', array)
} else {
array.push(value)
console.log('added', array)
}
break
}
}))
<div class="block">
<div class="string">some</div>
<div class="string">else</div>
<div class="string">other</div>
</div>