152

How can I add href attributes to <a></a> links dynamically using JavaScript?

<a href="dynamic url">Link</a>

9 Answers 9

262
const a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"
Sign up to request clarification or add additional context in comments.

8 Comments

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?
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
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 (w3.org/TR/DOM-Level-2-Core/core.html) doesn't seem to mention it.
These are the interfaces to interact with elements more easily. For examples, all links has the methods defined in HTMLLinkElement 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 <table> element (HTMLTableElement) where you can use insertRow() to insert new rows without having to create the <tr> and append it to the table.
@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 stackoverflow.com/questions/4456231/…
|
41

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");

7 Comments

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). developer.mozilla.org/en/DOM/element.setAttribute#Notes
@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 (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: 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?
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.
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.
|
11

More actual solution:

<a id="someId">Link</a>
const a = document.querySelector('#someId');
a.href = 'url';

1 Comment

querySelector is slower than getElementById.
9
document.getElementById('link-id').href = "new-href";

one-liner might be more suitable for some folks.

Comments

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>

3 Comments

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 <a></a> dynamically). However, this answer seems to be explaining how to create an a tag with an href.
@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.
This is a slightly cumbersome approach. For one it's polluting the DOM with an additional element unnecessarily just to select an element inside it rather than just adding that ID to the a tag and selecting it directly. It's also destroying and recreating the a tag using a string replace which is risky (the value of abc could break your html) and unnecessarily mutates the DOM when you can use element.setAttribute('href', abc)
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
}

Comments

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

Comments

-2

Single line solution

<a id="yourId">Link</a>
document.querySelector("#yourId").href("URL")

1 Comment

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

javasicript added

var x = "www.google.com";
vay y = "550";
var z= x+y;
document.write('<a href="' + z + '">GONDER</a>');

3 Comments

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.
this is the best method
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.