JavaScript: Set Anchor href Attribute

To the anchor href attribute on an HTML element with JavaScript, access the .href property and set it to the value you need.

 

JavaScript Example

Here is a demonstration of how we would do this on an anchor element with an ID in JavaScript.

 

<a href="" id="thing">Thing</a>
document.getElementById("thing").href = "https://www.example.com/";

 

JavaScript Class Example

Here is another example, this time looping through all anchors with a particular class and updating the href attribute.

 

var elms = document.getElementsByClassName('thing');

if (elms.length) {
  for (let i of elms) {
    i.href = 'https://example.com';
  }
}

 

jQuery Example

If you're using jQuery and would like to keep your code consistent, here is how we would do it for an anchor tag with an ID:

 

$('#foo').attr('href', 'https://example.com');