add class to all links that link to a certain domain with js (jquery)

后端 未结 4 1771
深忆病人
深忆病人 2020-12-17 00:26

If I have a bunch of links like this:

blah and this one and here is another 

        
相关标签:
4条回答
  • 2020-12-17 00:54

    to make sure you get http://foo.com, http://bar.foo.com/about, and not http://bazfoo.com, try:

    $("a[href*='/foo.com'], a[href*='.foo.com']").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\.com(\/.*|$)/i);
        })
        .addClass('your_class');
    

    Here are some test cases: http://jsbin.com/oruhu
    (you can edit it here: http://jsbin.com/oruhu/edit ).

    0 讨论(0)
  • 2020-12-17 01:01

    If you have links to distinct pages on the foo domain like:

    <a href="http://foo.com/eggs.html">
    <a href="http://foo.com/bacon.html">
    

    then you can use a selector like this:

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

    which will find all links that start with "http://foo.com/" or

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

    which will find all links that contain "/foo.com/"

    0 讨论(0)
  • 2020-12-17 01:06
    $("a[href='foo.com']").addClass('your_class')
    
    0 讨论(0)
  • 2020-12-17 01:08

    Trivially: $("a[href='http://foo.com']").addClass('foo'); But that assumes an exact match on the URL.

    0 讨论(0)
提交回复
热议问题