Adding Current class to the menu

Asked

Viewed 54 times

1

I’m having the problem in my JS it’s adding the Current class to all the #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");
});

3 answers

3


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

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

1

For this if you need to know the href of link / anchorage. So your dial lacks the last step inside each <li> go look for the anchor <a> and add a class.

For that you can use the .find() that accepts a CSS selector and searches the descendants of the initial element by returning the first element it finds. Then just add the class to the right element (li or a consonant).

$("#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
    }
});

1

Great solutions have already been cited, yet below is my contribution.

An interesting way to solve this would be to use a Attribute Contains Selector A 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 should be careful not to write absolute Urls us href they would become incompatible with window.location.pathname

Browser other questions tagged

You are not signed in. Login or sign up in order to post.