Setting the class of an object on load in jQuery

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • metaphysics
    New Member
    • May 2007
    • 59

    Setting the class of an object on load in jQuery

    I am trying to set the class of a "<li>" based on if the page is loaded with an anchor. For example, if http://www.example.com/index.html#services is loaded, I would like to change the class of li#nav_services to current. (The html would be <li id="nav_service s" class="current" >Services</li> after the change). How would I do this using jQuery?
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    You can get #services using the location.hash property. Then to add a class, use the addClass method.

    Comment

    • metaphysics
      New Member
      • May 2007
      • 59

      #3
      Okay, so if I have:

      Code:
      $(function(){
          var path = location.pathname.substring(1);
          if ( path )
              $('.navbar a[@href$="' + path + '"]').attr('class', 'current');
      });
      How do I get it to select the <li> that the <a> is nested in?

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        Using the ID selector #nav_services.

        Comment

        • metaphysics
          New Member
          • May 2007
          • 59

          #5
          Alright, thanks. I figured it out.

          Comment

          Working...