How to add class in jQuery to a particular element?

Asked

Viewed 373 times

1

I have a list containing "Urls" for other pages, I’m having difficulty to pick up the URL of the current page and check if the extracted pathname is in my list of Urls, if it exists I should add the 'active' class to the li that surrounds the link.

Following list mentioned above:

<ul class='nav navbar-nav navbar-right menuHover'>
    <li>
        <a href='/'>
            <span>
                Página Inicial
            </span>
        </a>
    </li>
    <li class='dropdown'>
        <a href='/cursos'>
            <span>
                Cursos
            </span>
        </a>
    </li>
    <li>
        <a href='contact3.html'>
            <span>
                Contato
            </span>
        </a>
    </li>
</ul>

The code below takes the pathname of the URL:

$(document).ready(function() {
    $(location).attr('href');
    var pathname = window.location.pathname.replace('#', '');
    alert(pathname);
});
  • Which Server-Side language is using ?

2 answers

2

You only need to cross each li (Oops! a) until you find one of them that contains a href equal to the location.pathname. Therefore, there is a better way to do this if you re-interpret the href of each li, turning it into a new instance of Location.

And why add a '/' at the beginning of each directory? Because the comparison of each directory against the directory of location.href could fail if I did not add, for example, if such a directory were equal to location.href, its comparison would still fail if it did not have a '/' in the beginning, as well as location.href could have.

(Location.href.pathname = "/dir";

(this.pathname = "dir")

(location.href.pathname = "/dir") === (this.pathname = "dir")
// false

To know if the directory does not contain a '/' at the beginning, just a condition like this: pathname.charAt(0) !== '/', since the directory is a String... ;]

$(document).ready(function() {
    var pathname = location.pathname.charAt(0) !== '/' ? 
                        location.pathname = '/' + location.pathname :
                        location.pathname

    $('.navbar-nav a').each(function() {
        var link = document.createElement('a')
        link.href = this.href
        if ((link.pathname.charAt(0) !== '/' ?
                        href = '/' + href :
                        href) === pathname) {
            $(this).addClass('active')
            return false
        }
    });
});

2


Below is an example working for the url of this site’s snippets (http://stacksnippets.net/js)

$(document).ready(function() {
    
    var pathname = location.pathname.replace('#', ''); 

    
    $('.nav a').each(function(){
      if($(this).attr('href') == pathname){
        $(this).addClass('active');
        return false;
      }
    });
    
});
.active{
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='nav navbar-nav navbar-right menuHover'>
    <li>
        <a href='/'>
            <span>
                Página Inicial
            </span>
        </a>
    </li>
    <li class='dropdown'>
        <a href='/cursos'>
            <span>
                Cursos
            </span>
        </a>
    </li>
    <li>
        <a href='contact3.html'>
            <span>
                Contato
            </span>
        </a>
    </li>
  <li>
        <a href='/js'>
            <span>
                Javascript
            </span>
        </a>
    </li>
</ul>

  • You could have broken the jQuery loop

  • @nicematt, as so "broken the loop"?

  • You know, right? jQuery.fn.each can be broken by returning exactly false in the callback of the loop. You could have broken the loop in the block of the if, since there is no need to go through the next li’s again. And your code can also be problematic if a link of li’s does not have a '/' at the beginning, as comparisons can fail against location.href. And this is the case of the question, there are li’s that do not have '/' at the beginning of their own links.

  • @nicematt, True... I hadn’t thought to prevent him from going through the unnecessary items.

  • About the '/' of the directories you can check in my answer to get a basic idea

Browser other questions tagged

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