How to change the href for a hyperlink using jQuery

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

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

12条回答
  •  时光取名叫无心
    2020-11-21 12:00

    href in an attribute, so you can change it using pure JavaScript, but if you already have jQuery injected in your page, don't worry, I will show it both ways:

    Imagine you have this href below:

    Alireza Dezfoolian
    

    And you like to change it the link...

    Using pure JavaScript without any library you can do:

    document.getElementById("ali").setAttribute("href", "https://stackoverflow.com");
    

    But also in jQuery you can do:

    $("#ali").attr("href", "https://stackoverflow.com");
    

    or

    $("#ali").prop("href", "https://stackoverflow.com");
    

    In this case, if you already have jQuery injected, probably jQuery one look shorter and more cross-browser...but other than that I go with the JS one...

提交回复
热议问题