Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2009-07-08
4
Medium Priority
?
958 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
ID: 24810709
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 2000 total points
ID: 24810756
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
ID: 24810791

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

Open in new window

0
 

Author Closing Comment

by:GhostWerx
ID: 31601424
Thanks heaps.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses four methods for overlaying images in a container on a web page
When crafting your “Why Us” page, there are a plethora of pitfalls to avoid. Follow these five tips, and you’ll be well on your way to creating an effective page.
In this tutorial viewers will learn how to embed custom externally-hosted Google Fonts using the Google Font API in CSS Go to the Google Fonts website at google.com/fonts: Browse or search based on font properties or name to find a suitable font for…
The viewer will learn how to dynamically set the form action using jQuery.

886 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