how can the value of an href attribute be changed using javascript/css?

后端 未结 4 1223
陌清茗
陌清茗 2021-01-29 12:19

Assuming that the html contains the following structure:



         


        
相关标签:
4条回答
  • 2021-01-29 12:34

    Put an id on it, e.g.

    <a id="the_a_tag" href="...">...</a>
       ^^^^^^^^^^^^^^
    

    then the JS is simply

    document.getElementById('the_a_tag').href = 'new address goes here';
    

    as long as you put the javascript AFTER the relevant HTML.

    And note: CSS is for presentation only. With a few exceptions, it cannot affect the content of document elements, merely how they appear (color/size/position/etc...).

    0 讨论(0)
  • 2021-01-29 12:39

    You could do it without id:

    document.querySelector("a[href^='http://the']")
    

    and set the href prop:

    document.querySelector("a[href^='http://the']").href=whatever
    

    For a full reference (browser-compatibility) of querySelector see the MDN-Article

    0 讨论(0)
  • 2021-01-29 12:43

    You can do this using something like this:

    document.getElementById("abc").href="xyz.php";
    

    You will need to set an ID for the tag, so your tag will look like this:

        <div>
        <a href="http://the/link/that/needs/to/be/changed">text</a>
    </div>
    
    <div>
        <div>
            //<script> or <style> must go here
        </div>
    </div>
    
    0 讨论(0)
  • 2021-01-29 12:52

    Give the link an id <a href='...' id='linkToChange'>text</a>

    And then access it in your script: document.getElementById('linkToChange').href='newAddress';

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