Is it possible to change the href of a link?
Here I have a link:
<a id="downloadLink">Donwload Link</a>
And a JavaScript function:
function ac(){document.getElementById('d开发者_JAVA技巧ownloadLink').href = "CS352ProjectProposalRequirements.pdf";}
However when I call the function it doesn't work. It gives an error:
Cannot change the property of null "href"
How can I dynamically change the href
of a link?
I believe you're getting an error because href
is not initially defined in your link. If you give it a default value initially (e.g. - #), you can change it later with JS.
<a id="downloadLink href="#" >DOWNLOAD</a>
.
This will fix the problem.
You can change or create the HREF attribute dynamically by using something like this:
document.getElementById('downloadlLink').attributes["href"] = "yourlink";
精彩评论