最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - add class to all links that link to a certain domain with js (jquery) - Stack Overflow

programmeradmin6浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 12

to 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.

发布评论

评论列表(0)

  1. 暂无评论