Pregunta

I got this Jq to add active class to <li> tag:

$("#main-nav li").each(function(index) {
        if(this.href.trim() == window.location)
            $(this).addClass("active");
            //alert(this.href.trim());
    });

html:

<div class="navbar-collapse collapse">
      <ul class="nav navbar-nav" id="main-nav">
        <li><a href="index.php">Home</a></li>
        <li><a href="about.php">About</a></li>
        <li><a href="contact.php">Contact</a></li>
</div>

But somehow it doesn't works, can anyone please look after what's goes wrong?

¿Fue útil?

Solución

You need to loop through the anchors, not the list items. The href is a property of the anchor. Do that loop and you can then apply .addClass() to the closest list item. Also, if you are using jQuery, you may as well use the reliable jQuery trim():

$("#main-nav li a").each(function(index) {
    if($.trim(this.href) == window.location) {
        $(this).closest('li').addClass("active");
        //alert(this.href.trim());
    }
});

Otros consejos

You are not going to get href using this.href.trim().you need to use:

$(this).find('a').attr('href').trim()

My version:

$("#main-nav li a").each(function(index) {
    if(this.href.trim() == window.location)
        $(this).parent().addClass("active");
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top