This post will discuss how to replace the text of an anchor tag in JavaScript and jQuery.

1. Using jQuery

With jQuery, you can use the text() method to replace the text of an anchors tag with a specific text. The following code demonstrates this.

JS


HTML



Edit in JSFiddle

 
Note that $('a') will match with all the anchors on the page. Alternatively, you can select anchors with specific classes or with a specific ID.

You can also use the html() method instead.

JS


HTML



Edit in JSFiddle

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 demonstrates this:

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

That’s all about replacing the text of an anchor tag in JavaScript and jQuery.