Link to home
Start Free TrialLog in
Avatar of GhostWerx
GhostWerxFlag for Australia

asked on

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

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.
Avatar of Chad Haney
Chad Haney
Flag of United States of America image

This should work.
$(document).ready(function(){
	$('a').each(
		function(){
			if($(this).attr('href')=="/another-page"){
			$(this).addClass("selected");
			}
	});
});

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Chad Haney
Chad Haney
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

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

Open in new window

Avatar of GhostWerx

ASKER

Thanks heaps.