简体   繁体   中英

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

If I have a bunch of links like this:

<a href="foo.com">blah</a> and this <a href="example.com">one</a> and here is another <a href="foo.com"></a>.

How would I add a class to all the links that link to foo.com?

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

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/"

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM