Solved

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

Posted on 2009-07-08
4
951 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 500 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Use these top 10 tips to master the art of email signature design. Create an email signature design that will easily wow recipients, promote your brand and highlight your professionalism.
Building a website can seem like a daunting task to the uninitiated but it really only requires knowledge of two basic languages: HTML and CSS.
In this tutorial viewers will learn how to style different bullet points for unordered lists in CSS. Begin with a normal unordered list; the default bullet point is a solid circle: In the CSS, create a defined class of unordered list by typing "ul.S…
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…

770 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