使用js(jquery)将链接添加到链接到某个域的所有链接

如果我有一堆像这样的链接:

blah and this one and here is another . 

如何将所有链接添加到链接到https://stackoverflow.com/questions/1713222/add-class-to-all-links-that-link-to-a-certain-domain-with-js-jquery/foo.com的链接?

为了确保你得到http://foo.com,http : //bar.foo.com/about ,而不是http://bazfoo.com ,试试:

 $("a[href*='/foo.com'], a[href*='.foo.com']").addClass('your_class'); 

这是一个使用正则表达式的更强大的解决方案,请注意,这可能比较慢,但检查域是否在开头:

 $("a").filter( function(){ return $(this).attr('href') .match(/^https?:\/\/([^/]*\.)?foo\.com(\/.*|$)/i); }) .addClass('your_class'); 

以下是一些测试用例: http : //jsbin.com/oruhu
(你可以在这里编辑它: http : //jsbin.com/oruhu/edit )。

如果您有foo域上不同页面的链接,例如:

   

然后你可以使用这样的选择器:

 $("a[href^=http://foo.com/]").addClass("newClass") 

它将找到所有以“ http://foo.com/ ”开头的链接

 $("a[href*=/foo.com/]").addClass("newClass") 

找到包含“/foo.com/”的所有链接

 $("a[href='foo.com']").addClass('your_class') 

琐碎的: $("a[href='http://foo.com']").addClass('foo'); 但这假设与URL完全匹配。