How do I add a Class on a page targeting a specific URL via jQuery?
+7
A:
I'm assuming you want to add a link to all anchor tags that have a specific href value?
You can filter your a
tag matches by the href
attribute using the following:
$('a[href="http://www.google.com"]').addClass("className");
GenericTypeTea
2010-08-19 08:35:18
+1 Consider using `^=` instead *if* you only want to match on the host, e.g. http://jsfiddle.net/sKsLv/1/
jensgram
2010-09-23 09:38:05
A:
either the answer by GenericTypeTea
or
$('a').each(function() {
if($(this).attr('href') == 'http://www.google.com') {
$(this).addClass('className');
}
});
MRW
2010-08-19 09:38:35
Thanks a lot guys, but I'm still lost where the script above add 'className' on the page. I added the script above on the header of my page and I don't see the 'className' anywhere on the page or on the URL?
Mali
2010-08-23 09:08:32
@Mali The CSS class `className` is added to the `<a>` elements. Consider using a DOM inspector like Firebug. Also, see my comment on @GenericTypeTea's answer.
jensgram
2010-09-23 09:39:21