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
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.
i found another way,
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
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.