Solved

jQuery to add class to link list item based on href value

Posted on 2009-07-08
4
948 Views
Last Modified: 2012-05-07
Hi all,

if I have the following code:

<ul>
<li><a href="/some-page">Some Page</a></li>
<li><a href="/another-page">Another Page</a></li>
</ul>

How can I use jQuery to add the class "selected" to the li based on the href="/another-page".

So jQuery scans the list, if the href value equals "/another-page" then add the selected class to the li element so I would then have the following code:

<ul>
<li><a href="/some-page">Some Page</a></li>
<li class="selected"><a href="/another-page">Another Page</a></li>
</ul>

Thanks for your help.

GW.
0
Comment
Question by:GhostWerx
  • 2
4 Comments
 
LVL 12

Expert Comment

by:Chad Haney
Comment Utility
This should work.
$(document).ready(function(){

	$('a').each(

		function(){

			if($(this).attr('href')=="/another-page"){

			$(this).addClass("selected");

			}

	});

});

Open in new window

0
 
LVL 12

Accepted Solution

by:
Chad Haney earned 500 total points
Comment Utility
Oh sorry just realized you want the class on the li not the anchor tag.
$(document).ready(function(){

	$('ul a').each(

		function(){

			if($(this).attr('href')=="/another-page"){

			$(this).parent().addClass("selected");

			}

	});

});

Open in new window

0
 
LVL 82

Expert Comment

by:hielo
Comment Utility

$("li a[href='/another-page']").parent().addClass("selected")

Open in new window

0
 

Author Closing Comment

by:GhostWerx
Comment Utility
Thanks heaps.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
The viewer will learn how to dynamically set the form action using jQuery.
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now