I'm currently working on a handleClick function for a gradient swatch gallery. The goal is to add an id of "bg-gradient" to the clicked element, and if another swatch is clicked, remove that id from the previously clicked swatch and add it to the newly clicked one. Essentially, only one element should have the id"bg-gradient" at any given time. Although my code is close to working, it currently adds the id to every clicked swatch, which is not the desired behavior. I believe this issue should be relatively simple to resolve, but I'm struggling to make it work. Please see the code snippet below and the attached screenshot showing the problem (all 4 swatches getting the id).
handleSwatch(){
let el = document.querySelectorAll('.swatch');
for(let i=0; i < el.length; i++) {
el[i].addEventListener('click', function () {
if (!document.querySelector("swatch#bg-gradient")) {
el[i].setAttribute('id', 'gradient');
} else {
alert('Element exists!');
}
});
}
}
}
[![Remove first (or set if not exist), add new id to clicked element][1]][1]
Thanks