I am retrieving all users from the database using this code snippet
fetch("/api/v1/users", {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(function(res) {
return res.json();
})
.then(function(json) {
json.data.forEach((elem) => {
Object.values(elem).forEach((item) => {
if(item != "" && typeof item == "string") {
document.querySelector('.users__list').appendChild(users.createElement('div', 'users__user-field', '', `<p>${item}</p>`))
}
})
})
})
Once the users are fetched, I create an element and append it to the list. This process works without any issues, but there's a problem!
The following section of code is causing an issue
const selectableUsers = {
users: document.querySelectorAll('.users__user-field'),
click(elem) {
this.reset()
elem.classList.toggle('selected')
},
reset() {
this.users.forEach((elem) => {
elem.classList.remove('selected')
})
}
}
window.onload = () => {
document.querySelectorAll('.users__user-field').forEach((elem) => {elem.addEventListener('click', () => {selectableUsers.click(elem)})})
}
In my algorithm, after generating elements and loading the window, all items with the class users__user-field
should have a click event to toggle the selected
class. However, this functionality doesn't seem to be working as intended. I'm not sure why. Can you assist me?