'HTML - How to select one id from a list of ids in querySelector
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();
};
Solution 1:[1]
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();
}
});
Solution 2:[2]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | CertainPerformance |
Solution 2 |