I have the following HTML structure:
<div id="settings-choose">
<a href="#setting1" class="setting-tab">
<div class="content">
<div class="icon setting1-off"></div>
<div class="label">Setting 1</div>
</div>
</a>
<a href="#setting2" class="setting-tab">
<div class="content">
<div class="icon setting2-off"></div>
<div class="label">Setting 2</div>
</div>
</a>
<!-- more .setting-tab elements -->
</div>
Whenever I click on one of the .setting-tab elements, I want to:
- Add the class
.selectedto that.setting-tabelement (and remove it from the others) - Replace the “
-off” part of the class on its child.iconelement with “-on” (and flip all of the others to “-off“)
I can do #1 successfully, but not #2. Here’s what I have:
$("#settings-choose .setting-tab").click(function(){
$("#settings-choose .setting-tab").removeClass("selected");
$(this).addClass("selected");
$("#settings-choose .setting-tab").each(function(){
var icon = $(this).find(".icon"),
state = icon.attr("class");
if (!($(this).hasClass("selected"))){
state.replace("-on", "-off");
} else {
state.replace("-off", "-on");
}
});
});
This correctly adds the .selected class to whichever .setting-tab element was clicked and removes it from the others…
<a href="#setting1" class="setting-tab selected">...</a>
<a href="#setting2" class="setting-tab">...</a>
But the class of the .icon element doesn’t change…
<a href="#setting1" class="setting-tab selected">
<div class="content">
<div class="icon setting1-off"></div>
<div class="label">Setting 1</div>
</div>
</a>
I don’t get any errors in the console, just…it doesn’t change.
Any ideas where I’m going wrong?
Quick answer is you forgot the assign value for class just replacing a text in the variable.
but you can make other changes to for example
instead