I have three identical items in the DOM. Specifically, I am referring to a moving line
<span class="caret"></span>
<ul>
<li class="nav-item-1">
<a href="#">ITEM 1</a>
<span class="caret"></span>
</li>
</ul>
<ul>
<li class="nav-item-2">
<a href="#">ITEM 2</a>
<span class="caret"></span>
</li>
</ul>
<ul>
<li class="nav-item-3">
<a href="#">ITEM 3</a>
<span class="caret"></span>
</li>
</ul>
Scenario: When I click on the first
<span class="caret"></span>
, it should receive the class "open"
, while the others remain with only the class "caret"
. When I click on the second <span class="caret"></span>
, it should also receive the class "open"
, and the first one should lose this class. Is this achievable? My attempted solution is as follows:
$(".caret").click(function () {
$(this).data('clicked', true);
if ($('.caret').data('clicked')) {
$(".caret").toggleClass('opened');
}
});
Although this solution works, it applies the toggleClass('opened')
to all elements with the class "caret"
instead of just the one that was clicked.