469,337 Members | 6,009 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,337 developers. It's quick & easy.

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_services" class="current">Services</li> after the change). How would I do this using jQuery?
Jan 30 '09 #1
4 3981
acoder
16,027 Expert Mod 8TB
You can get #services using the location.hash property. Then to add a class, use the addClass method.
Jan 30 '09 #2
Okay, so if I have:

Expand|Select|Wrap|Line Numbers
  1. $(function(){
  2.     var path = location.pathname.substring(1);
  3.     if ( path )
  4.         $('.navbar a[@href$="' + path + '"]').attr('class', 'current');
  5. });
How do I get it to select the <li> that the <a> is nested in?
Jan 30 '09 #3
acoder
16,027 Expert Mod 8TB
Using the ID selector #nav_services.
Jan 31 '09 #4
Alright, thanks. I figured it out.
Jan 31 '09 #5

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

8 posts views Thread by =?iso-8859-1?q?Jean-S=E9bastien?= | last post: by
7 posts views Thread by Dave Fowler | last post: by
1 post views Thread by DuaneMoraes | last post: by
26 posts views Thread by RobG | last post: by
53 posts views Thread by souporpower | last post: by
3 posts views Thread by mberkom | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by Marylou17 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.