136

How can I add the href attribute to a link dynamically using JavaScript?

I basically want to add a href attribute to <a></a> dynamically (i.e. when the user clicks on specific image in the website).

So from:

<a>Link</a>

I need to go to:

<a href="somelink url">Link</a>
Michael Currie
  • 13,721
  • 9
  • 42
  • 58
Pavel
  • 5,213
  • 10
  • 34
  • 47

9 Answers9

241
var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"
stecb
  • 14,478
  • 2
  • 50
  • 68
  • Interesting. I didn't know you could directly access the attributes as fields (compare to my solution below, using `setAttribute`). Does anybody know if this approach is standard? – mgiuca Jan 14 '11 at 08:53
  • I think on the a DOM element href is an attribute you can set directly by el.href. Instead, setAttribute(el,attr) is used to add some custom attributes to a particular DOM element, so in this case there's no need to use it to set a std. attr – stecb Jan 14 '11 at 08:57
  • But are both ways *correct*? Not trying to criticise the answer -- it may well be correct. But on the web, it isn't sufficient to get something that works for you. It needs to work in all browsers, and that means you need to follow standards. FWIW, this works for me too (in Firefox), but I'm interested to know whether it is actually a standard way to do it. The W3C DOM specification (http://www.w3.org/TR/DOM-Level-2-Core/core.html) doesn't seem to mention it. – mgiuca Jan 14 '11 at 08:59
  • 7
    These are the interfaces to interact with elements more easily. For examples, all links has the methods defined in [`HTMLLinkElement`](http://krook.org/jsdom/HTMLLinkElement.html) which supports setting certain fields such as `href`. You have to look in the reference to see which one you can use without having to `setAttribute`. Another example is the `` element ([HTMLTableElement](http://krook.org/jsdom/HTMLTableElement.html)) where you can use `insertRow()` to insert new rows without having to create the `` and append it to the table.
    – Thai Jan 14 '11 at 09:00
  • And yes, setting `.href` is the standard way of setting it. `setAttribute()` is also supported. – Thai Jan 14 '11 at 09:03
  • @Thai OK great that answers my question. I was citing the DOM Core, but it turns out you have to look in the DOM HTML extensions (http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html#ID-35143001). So each element has a certain set of properties which can be used; `setAttribute` is more general. – mgiuca Jan 14 '11 at 09:10
  • @mgiuca exactly! setAttribute could be thought of a custom attribute manager :) – stecb Jan 14 '11 at 09:15
  • 3
    @mgiuca: In general for HTML DOMs, you should prefer using properties rather than `setAttribute()` and `getAttribute()`, which are broken in IE and don't always do what you might expect. See http://stackoverflow.com/questions/4456231/retrieving-html-attribute-values-the-dom-0-way/4456805#4456805 – Tim Down Jan 14 '11 at 10:31
37

I assume you know how to get the DOM object for the <a> element (use document.getElementById or some other method).

To add any attribute, just use the setAttribute method on the DOM object:

a = document.getElementById(...);
a.setAttribute("href", "somelink url");
mgiuca
  • 20,958
  • 7
  • 54
  • 70
  • 1
    pal, setattribute is pretty non-standard for modifying attributes. To access or modify the current values, you should use the properties. For example, use elt.value instead of elt.setAttribute('value', val). https://developer.mozilla.org/en/DOM/element.setAttribute#Notes – naveen Jan 14 '11 at 08:59
  • 1
    @naveen It says "most notably in XUL", which is presumably not what this is. I'm not sure which other values it refers to ("certain attributes" is very vague), but `setAttribute` is clearly the standard (http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-F68F082), and W3C doesn't define any attributes it doesn't work for. Conversely, I can guarantee that using the property will fail for certain attribute names. Such as `tagName`, and `setAttribute` -- those are already fields/methods of the Element interface. I don't see anywhere in the W3C document which mentions properties for attributes. – mgiuca Jan 14 '11 at 09:06
  • 1
    @mgiuca: It seems you found the relevant spec after posting that last comment. I don't understand your point about properties failing, and then mentioning `tagName`. Are you talking about custom attributes? – Tim Down Jan 14 '11 at 10:35
  • 1
    I mean that DOM (even as implemented in the browser) is a generic spec for working with XML trees in general, not just HTML. When working with arbitrary XML elements, the only way to reliably get and set attributes is `getAttribute` and `setAttribute`; `"tagName"` is an example of an attribute that can't work as a property. Only when working with HTML, and for certain attributes defined in the DOM HTML spec, can you use the properties to read and assign attributes. – mgiuca Jan 15 '11 at 22:16
  • I'm probably misunderstanding, but that's still confusing. `tagName` **is** a property of `Element` objects in JavaScript, in both HTML and XML DOMs, and you cannot get an element's tag name via `getAttribute("tagName")` (except in IE, whose implementation of `getAttribute()` and `setAttribute()` is broken), which seems precisely the opposite of what you're saying. – Tim Down Jan 16 '11 at 01:09
  • Yeah it was a confusing example, but what I'm talking about only works for confusing examples. I'm not talking about the `tagName` property (that is, the member of Element objects which tells you the tag name of the element). I'm talking about a hypothetical XML element with an attribute called `tagName`. For example, ``. You could not get the "foo" out of that element using `elem.tagName`, because that name is reserved. You would have to use `elem.getAttribute("tagName")` which is the generic way to read XML attributes. – mgiuca Jan 16 '11 at 03:45
  • Aaahhh, now I understand. Yes, you're right. With XML you haven't really got an option anyway: attribute-related properties simply don't exist. Thanks for clarifying. – Tim Down Jan 17 '11 at 11:02
8
document.getElementById('link-id').href = "new-href";

I know this is an old post, but here's a one-liner that might be more suitable for some folks.

noɥʇʎԀʎzɐɹƆ
  • 9,967
  • 2
  • 50
  • 67
7

First, try changing <a>Link</a> to <span id=test><a>Link</a></span>.

Then, add something like this in the javascript function that you're calling:

var abc = 'somelink';
document.getElementById('test').innerHTML = '<a href="' + abc + '">Link</a>';

This way the link will look like this:

<a href="somelink">Link</a>
Moishe Lipsker
  • 2,974
  • 2
  • 21
  • 29
Rahul Sudha
  • 137
  • 2
  • 7
  • Hi. Welcome to Stackoverflow. The OP's question seems to be about how to add an `href` to an **existing** `a` tag (*I basically want to add a href attribute to dynamically*). However, this answer seems to be explaining how to **create** an `a` tag with an `href`. – Moishe Lipsker Dec 28 '16 at 08:10
  • @MoisheLipsker It still works. Even if it does destroy the original, it does still in a way "set" the href. However, it is not practical as it does not retain the previous link without destroying it, thus potentially destroying other attributes and information. – Reality May 17 '21 at 19:41
6

More actual solution:

<a id="someId">Link</a>

const a = document.querySelector('#someId');
a.href = 'url';
Seldo97
  • 611
  • 1
  • 8
  • 17
0

I know there seems plenty good answers here, but none of them seemed simple enough for what I was "told" to do in the 2022 Udemy Web Development Bootcamp by Angela.

So I remembered how simple the use of scriplets was and figured to try it and it works just as well.

For those like me who are learning let me explain: . - takes you to current URL then static path then dynamic variable generated for each post (its a blog website)

<a href="./posts/<%= post.title %>">Read More</a>

This is using JS inside an EJS page

same solution is also given in the solution lecture of the bootcamp here: https://www.udemy.com/course/the-complete-web-development-bootcamp/learn/lecture/12385596#overview

Lecture 317

-1

I came here because I wanted to dynamically set the link href after it's been clicked

<a id='dynamic'>link text</a>

document.getElementById("dynamic").addEventListener("click", onClick_dynamic)

function onClick_dynamic(e){
    const nextPage = getNextPage()
    document.getElementById("dynamic").href = _BASE_URL + "?nextPage=" + nextPage
    // e.default processing sends user to href
}
kztd
  • 3,121
  • 1
  • 20
  • 18
-2

Single line solution

<a id="yourId">Link</a>
document.querySelector("#yourId").href("URL")
  • Welcome to SO! Please take a look at the other answers that were given before. Your approach is mentioned there already. In order to keep the site clear and make it easy to find answers, we try to avoid double answers. – ahuemmer Dec 29 '22 at 11:03
-4

javasicript added

var x = "www.google.com";
vay y = "550";
var z= x+y;
document.write('<a href="' + z + '">GONDER</a>');
Yasin İPEK
  • 54
  • 10
  • They want to change an existing link instead of creating a new one. Plus, `document.write` is a horrible method that rarely should even be thought about for use. – Reality May 16 '21 at 17:37
  • this is the best method – Yasin İPEK May 17 '21 at 18:44
  • Not even close. It is very dangerous, as XSS is very easy in your method. In addition, document.write clears the entire webpage. Another problem you have with your answer is that the OP (original poster) here does not want a *new* link, but rather an *existing* link, and they want it to have the href of it edited. – Reality May 17 '21 at 19:27