how can the value of an href attribute be changed

2020-05-09 23:31发布

Assuming that the html contains the following structure:

<div>
    <a href="http://the/link/that/needs/to/be/changed">text</a>
</div>

<div>
    <div>
        //<script> or <style> must go here
    </div>
</div>

...and assuming that the 'contribution' to the final HTML file can be inserted ONLY at the specified location, and assuming that the markup for the "a" element cannot be modified in any way, is it possible to add javascript or css code that will change the url that the href attribute of the previous "a" element refers to? If so, how?

4条回答
冷血范
2楼-- · 2020-05-09 23:34

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

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

查看更多
女痞
3楼-- · 2020-05-09 23:48

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

查看更多
Animai°情兽
4楼-- · 2020-05-09 23:51

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

查看更多
再贱就再见
5楼-- · 2020-05-10 00:00

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>
查看更多
登录 后发表回答