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

后端 未结 4 1786
深忆病人
深忆病人 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 ).

提交回复
热议问题