If I have a bunch of links like this:
<a href="foo">blah</a> and this <a href="example">one</a> and here is another <a href="foo"></a>.
How would I add a class to all the links that link to foo?
If I have a bunch of links like this:
<a href="foo.">blah</a> and this <a href="example.">one</a> and here is another <a href="foo."></a>.
How would I add a class to all the links that link to foo.?
Share Improve this question asked Nov 11, 2009 at 5:27 AmirAmir 2,2777 gold badges35 silver badges48 bronze badges4 Answers
Reset to default 12to make sure you get http://foo., http://bar.foo./about, and not http://bazfoo., try:
$("a[href*='/foo.'], a[href*='.foo.']").addClass('your_class');
Here's a stronger solution with regular expressions, this is probably slower, mind you, but checks the domain is on the start:
$("a").filter(
function(){
return $(this).attr('href')
.match(/^https?:\/\/([^/]*\.)?foo\.(\/.*|$)/i);
})
.addClass('your_class');
Here are some test cases: http://jsbin./oruhu
(you can edit it here: http://jsbin./oruhu/edit ).
If you have links to distinct pages on the foo domain like:
<a href="http://foo./eggs.html">
<a href="http://foo./bacon.html">
then you can use a selector like this:
$("a[href^=http://foo./]").addClass("newClass")
which will find all links that start with "http://foo./" or
$("a[href*=/foo./]").addClass("newClass")
which will find all links that contain "/foo./"
$("a[href='foo.']").addClass('your_class')
Trivially:
$("a[href='http://foo.']").addClass('foo');
But that assumes an exact match on the URL.