How to remove redundant class name when current classname is selected for color previewer ?

Probably butched on title. i have 9 color div, when one is clicked necessary js code is applied to get the class name of that div and it is then set as the primary color for the previewer. the issue is the class name keeps on adding to the previewer, is ther ea way to apply only one class? https://codepen.io/avinash-tallapaneni/pen/rNqVMKZ
3 Replies
Chris Bolson
Chris Bolson2y ago
Rather than using toggle you should probably be using add and remove. So, when you add a new color, you specifically remove the previous one. Toggle will only toggle the class name that you are sending it. If you click on one color button and then another one, the toggle action will have. O affect in the previous color so it remains on the element.
Avinash
AvinashOP2y ago
i found another way,
cardLabelColorPreview.classList.forEach((className) => {
if (className.startsWith("label-color-")) {
cardLabelColorPreview.classList.remove(className);
}
});
cardLabelColorPreview.classList.add(tempColor);
cardLabelColorPreview.classList.forEach((className) => {
if (className.startsWith("label-color-")) {
cardLabelColorPreview.classList.remove(className);
}
});
cardLabelColorPreview.classList.add(tempColor);
so each time when i click "label-color" is being added so here i used the property startsWith to check if there is a class name that starts with label -color if so then i remove that . DOnt know if this is the right method but it works thumbup
Chris Bolson
Chris Bolson2y ago
that is basically what I was saying. First your remove the classes previously added, then you add the one that you clicked on. Just to mention an alternative to looping through the existing classes would be to save the selected class name in a variable and use the variable to directly remove the class before then adding the new one assigning the new class name to the variable. This might be more flexible in case you change your naming convention and also removes the need to loop through the element classes. But the end result would be the same.
Want results from more Discord servers?
Add your server