How to change the href for a hyperlink using jQuery

前端 未结 12 2144
孤街浪徒
孤街浪徒 2020-11-21 11:15

How can you change the href for a hyperlink using jQuery?

12条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 11:40

    The simple way to do so is :

    Attr function (since jQuery version 1.0)

    $("a").attr("href", "https://stackoverflow.com/") 
    

    or

    Prop function (since jQuery version 1.6)

    $("a").prop("href", "https://stackoverflow.com/")
    

    Also, the advantage of above way is that if selector selects a single anchor, it will update that anchor only and if selector returns a group of anchor, it will update the specific group through one statement only.

    Now, there are lot of ways to identify exact anchor or group of anchors:

    Quite Simple Ones:

    1. Select anchor through tag name : $("a")
    2. Select anchor through index: $("a:eq(0)")
    3. Select anchor for specific classes (as in this class only anchors with class active) : $("a.active")
    4. Selecting anchors with specific ID (here in example profileLink ID) : $("a#proileLink")
    5. Selecting first anchor href: $("a:first")

    More useful ones:

    1. Selecting all elements with href attribute : $("[href]")
    2. Selecting all anchors with specific href: $("a[href='www.stackoverflow.com']")
    3. Selecting all anchors not having specific href: $("a[href!='www.stackoverflow.com']")
    4. Selecting all anchors with href containing specific URL: $("a[href*='www.stackoverflow.com']")
    5. Selecting all anchors with href starting with specific URL: $("a[href^='www.stackoverflow.com']")
    6. Selecting all anchors with href ending with specific URL: $("a[href$='www.stackoverflow.com']")

    Now, if you want to amend specific URLs, you can do that as:

    For instance if you want to add proxy website for all the URLs going to google.com, you can implement it as follows:

    $("a[href^='http://www.google.com']")
       .each(function()
       { 
          this.href = this.href.replace(/http:\/\/www.google.com\//gi, function (x) {
            return "http://proxywebsite.com/?query="+encodeURIComponent(x);
        });
       });
    

提交回复
热议问题