This post will discuss how to change href for an anchor tag in JavaScript and jQuery.

1. Using jQuery

With jQuery, you can use the .prop() method to set the DOM element property for the set of matched elements. The following code uses prop() to modify the href of all anchor tags on the page.

JS


HTML



Edit in JSFiddle

 
To select anchors with a specific href, you can do like:

JS


HTML



Edit in JSFiddle

 
This will match the anchor with a specific href on the page. Alternatively, you can select anchors with specific classes or specific ID.

2. Using JavaScript

In vanilla JavaScript, this is very simple. The following code demonstrates this with querySelector(), which returns the first anchor tag within the document.

JS


HTML



Edit in JSFiddle

 
Alternatively, you can use the querySelectorAll() method, which can return a list of all anchor elements within the document. The following code uses a common looping statement to access the matches.

JS


HTML



Edit in JSFiddle

 
If you want to be more specific, you can use the getElementById() method, which returns the anchor tag matching the specified ID.

JS


HTML



Edit in JSFiddle

 
This can also be done using the setAttribute() method, which sets the value of an attribute on the specified element.

JS


HTML



Edit in JSFiddle

That’s all about changing href for an anchor tag in JavaScript and jQuery.