471,887 Members | 1,263 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,887 software developers and data experts.

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 4026
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
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
reply views Thread by YellowAndGreen | last post: by
reply views Thread by zermasroor | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.