Reputation: 106
I have a list of buttons, each of these when clicked should console log the results of a different function.
<button>Log baseData</button>
<button>Log baseData in reverse</button>
<button>Log baseData without first item</button>
<button>Log each baseData entry as a new log</button>
I have tried a forEach loop, but can't figure out how to select each of these and fire different functions without adding an onClick attribute to the selected element. Any ideas? Thanks
let btns = document.querySelectorAll('button');
btns.forEach((i)=>{
i.addEventListener('click', ()=>{
console.log(baseData, i);
});
});
Upvotes: 0
Views: 140
Reputation: 335
You can define an object with connections buttonId
-functionName
and do something like:
function handler1() {
console.log(1);
}
function handler2() {
console.log(2);
}
function handler3() {
console.log(3);
}
function handler4() {
console.log(4);
}
const btns = document.querySelectorAll('button');
const handlers = {
func1: handler1,
func2: handler2,
func3: handler3,
func4: handler4,
}
btns.forEach(btn => {
const id = btn.getAttribute('id');
btn.addEventListener('click', handlers[id]);
});
<button id="func1">Log baseData</button>
<button id="func2">Log baseData in reverse</button>
<button id="func3">Log baseData without first item</button>
<button id="func4">Log each baseData entry as a new log</button>
Upvotes: 0
Reputation: 219047
You have a collection of button elements:
let btns = document.querySelectorAll('button');
According to comments on the question:
I'm looking to assign different functions to each button. E.g. if first buttons is clicked => console.log (baseData), if second button is clicked => console.log (somethingElse)
and:
I'll have to go with the current markup.
Then the "first button" is btns[0]
, the "second button" is btns[1]
, and so on. You can just assign handlers to each one:
let btns = document.querySelectorAll('button');
btns[0].addEventListener('click', ()=>{
console.log(baseData);
});
btns[1].addEventListener('click', ()=>{
console.log(somethingElse);
});
// etc.
This generally isn't a recommended approach because if the markup ever changes then you could be assigning the wrong functionality to each button. But if you are indeed tightly coupled to the exact markup you have then this is probably all you can do. At a business level the responsibility of that coupling is held by whatever prevents the markup from being modified.
Upvotes: 1