tags:

views:

57

answers:

2

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
+1 Consider using `^=` instead *if* you only want to match on the host, e.g. http://jsfiddle.net/sKsLv/1/
jensgram
A: 

either the answer by GenericTypeTea

or

$('a').each(function() {
    if($(this).attr('href') == 'http://www.google.com') {
        $(this).addClass('className');
    }
});
MRW
Thanks... but seriously, **never** do this.
GenericTypeTea
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
@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