To answer your question in the comment on the first answer, .parents ('li') will get all the parents you found when you approach the DOM from your current position. Addendum: the first pseudo selector ensures that you get the first one found.
The best solution is to use .parent (singular). For example: $thisLi.parent('ul') . I do not believe that this is your problem, though ...
Is it possible that the browser just loads a new page? I donโt see you calling event.preventDefault() , because you are not writing the event to your code, you are simply responding to it ...
In addition, .on is the preferred way to bind to events now:
$(function(){ $('.nav li a').on('click', function(e){ e.preventDefault(); // prevent link click if necessary? var $thisLi = $(this).parent('li'); var $ul = $thisLi.parent('ul'); if (!$thisLi.hasClass('active')) { $ul.find('li.active').removeClass('active'); $thisLi.addClass('active'); } }) })
source share