I have an array of :
const buttons = ["home","menu","contact"]
I iterate through buttons using foreach
.
buttons.forEach(btn => {
let button = document.getElementById(btn)
button.addEventListener('click',()=>{
button.classList.add('selected')
})
});
As you can see i have added a classlist for each button using eventlistener. But i want to remove classlist of previous button when clicked other button.
Thank you!
CodePudding user response:
If you click one button then other button classList will be removed. Here is the code.
const buttons = ["home", "menu", "contact"]
buttons.forEach((btn, index) => {
let button = document.getElementById(btn)
button.addEventListener("click", () => {
buttons.forEach(btnA => {
document.getElementById(btnA).classList.remove("selected");
})
button.classList.add("selected");
})
});
.selected {
color: red;
}
<button id="home">Home</button>
<button id="menu">Menu</button>
<button id="contact">Contact</button>
CodePudding user response:
See Parameters
section here
buttons.forEach((btn, index, arr) => {
const previous = index > 0 ? arr[index-1] : null;
let button = document.getElementById(btn)
button.addEventListener('click', ()=> {
button.classList.add('selected')
})
});
Or you can use pairwise
helper method e.g.
function pairwise<T>(array: Array<T>): Array<[T, T]> {
return array.map((item, i, arr) => {
if (i < arr.length) {
return [arr[i], arr[i 1]]
}
}).slice(0, -1);
}
This will transform given array to pairs e.g.
[1, 2, 3] => [[1, 2], [2, 3]]