I would like to change all elements in a list except the one that is clicked. I suppose I need to determine what is actually clicked and then change it’s siblings? How do I find which element is clicked?
<ul>
<li><h4 class="span1"><a href="#" class="sort" data-sort="ID">ID<i class="icon-arrow-down" aria-hidden="true"></i></a></h4></li>
<li><h4 class="span2"><a href="#" class="sort" data-sort="Type">Type<i class="icon-arrow-down" aria-hidden="true"></i></a></h4></li>
<li><h4 class="span3"><a href="#" class="sort" data-sort="Task">Task<i class="icon-arrow-down" aria-hidden="true"></i></a></h4></li>
<li><h4 class="span8"><a href="#" class="sort" data-sort="Project">Project<i class="icon-arrow-down" aria-hidden="true"></i></a></h4></li>
<li><h4 class="span3a"><a href="#" class="sort" data-sort="DueDate">Urgency<i class="icon-arrow-down" aria-hidden="true"></i></a></h4></li>
<li><h4 class="span3 last"><a href="#" class="sort" data-sort="Created">Date Created<i class="icon-arrow-down" aria-hidden="true"></i></a></h4></li>
</ul>
$('.sort').click(function () {
$(this).data('clicked', true);
if($(this).data('clicked')) {
$('i', this).toggleClass('icon-arrow-down').toggleClass('icon-arrow-up');
}
else {
$('.sort i').siblings().removeClass('icon-arrow-up').addClass('icon-arrow-down');
}
});
Answer:
$('.sort').click(function() {
$(this).closest('li').siblings().find('i').removeClass('icon-arrow-up').addClass('icon-arrow-down');
$(this).find('i').toggleClass('icon-arrow-down icon-arrow-up');
});
Since the
$(this)represents the anchor element clicked,siblings()can’t access the otherlielements. Instead, look for the siblings of the element two levels above, like this:Or change the markup so that you’re targeting the
liinstead of the anchor contained within.