最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - how can the value of an href attribute be changed using javascriptcss? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Jun 17, 2013 at 20:21 J Smith asked Jun 17, 2013 at 19:19 J SmithJ Smith 2,4153 gold badges22 silver badges37 bronze badges 2
  • 1 See stackoverflow./questions/179713/… – ForOhFor Commented Jun 17, 2013 at 19:21
  • If you want to get the previous a element and cannot change the HTML, this should do: var elements = document.getElementsByTagName('a'); var last = elements[elements.length - 1];. – Felix Kling Commented Jun 17, 2013 at 19:22
Add a ment  | 

4 Answers 4

Reset to default 3

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-patibility) of querySelector see the MDN-Article

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

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

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

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)

  1. 暂无评论