Adding current class to the menu

1

I'm having the problem in my JS it's adding the Current class to all #li.

html

<ul id="navlist">
    <li id="home"><a href="/">Home</a></li>
    <li id="sobre"><a href="/sobre">Sobre</a>
    </li>
</ul>

jquery

alert(window.location.pathname);
$("#navlist li").each(function(){
    if($(this).attr("href")==window.location.pathname)
        $(this).addClass("current");
});
    
asked by anonymous 26.03.2015 / 14:38

3 answers

3

Make the following change, it was not working because in the <li> tag there is no href attribute and with .children() it takes the child element that in this case would be <a> has the href attribute

alert(window.location.pathname);
$("#navlist li").each(function(){
    if($(this).children().attr("href")==window.location.pathname)
        $(this).addClass("current");
});
    
26.03.2015 / 14:41
1

For this if you need to know the href of the link / anchor . So in your selector it lacks the last step that is inside every <li> go look for the ancora <a> and add a class.

For this you can use .find() that accepts a CSS selector and searches the descendants of the starting element by returning the first element to find. Then you just have to add the class to the right element ( li or a as you want).

$("#navlist li").each(function(){
    var $ancora = $(this).find('a');
    if($ancora.attr("href") == window.location.pathname){
        $(this).addClass("current");
        // ou $ancora.addClass("current"); se a classe fôr para adicionar ao link
    }
});
    
26.03.2015 / 14:52
1

Great solutions have already been mentioned, but my contribution is below.

An interesting way to resolve this would be to use a Attribute Contains Selector One Selector a little more specific.

 $("#navlist li a[href='"+window.location.pathname+"']").parent().addClass("current");
  

NOTE: As discussed @Sergio and I conclude that the developer   When using this solution you should be careful not to write absolute URLs   as% would be incompatible with    href

    
26.03.2015 / 15:09