I am writing the following codes. There are repeating codes for the same function. I wonder if there is a way to include all the ids in one querySelector such that there are no repeats. Only the id in the selector is different.
The code is here:
function refreshMessage() {
courseSocket.send(JSON.stringify({
'message': 1
}));
};
document.querySelector('#next-student').onclick = function(e) {
refreshMessage();
};
document.querySelector('#put-back').onclick = function(e) {
refreshMessage();
};
document.querySelector('#invite').onclick = function(e) {
refreshMessage();
};
document.querySelector('#clear-queue').onclick = function(e) {
refreshMessage();
};
CodePudding user response:
Iterate over all selectors...
const ids = ['next-student', 'put-back', 'invite', 'clear-queue'];
for (const id of ids) {
document.getElementById(id).onclick = refreshMessage;
}
Or use event delegation
document.addEventListener('click', (e) => {
if (e.target.closest('#next-student, #put-back, #invite, #clear-queue')) {
refreshMessage();
}
});
CodePudding user response:
Use querySelectorAll
document.querySelectorAll("#next-student, #put-back, #invite, #clear-queue,[name=rdoGroup]").forEach(function(element) {
element.onclick = function(e) {
refreshMessage();
}
});
function refreshMessage(){
console.log("REFRESHING!");
}
<button id="next-student">Next</button>
<button id="put-back">Put Back</button>
<button id="invite">Invite</button>
<button id="clear-queue">Clear</button>
<label><input type="radio" name="rdoGroup"> Yes</label>
<label><input type="radio" name="rdoGroup"> No</label>
Or better yet, which preserves any existing on click listeners:
let selectors = ["#next-student", "#put-back", "#invite", "#clear-queue", "[name=rdoGroup]"];
document.querySelectorAll(selectors.join(",")).forEach(function(element) {
element.addEventListener("click", refreshMessage);
});
function refreshMessage() {
console.log("REFRESHING!");
}
<button id="next-student">Next</button>
<button id="put-back">Put Back</button>
<button id="invite">Invite</button>
<button id="clear-queue">Clear</button>
<label><input type="radio" name="rdoGroup"> Yes</label>
<label><input type="radio" name="rdoGroup"> No</label>