Replace text of an anchor tag with JavaScript/jQuery
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
|
1 2 3 4 5 |
$(document).ready(function() { $("#submit").click(function() { $("a").text('Bing it!'); }) }); |
HTML
|
1 2 3 4 5 6 7 8 9 |
<!doctype html> <html lang="en"> <body> <a href="https://www.bing.com/">Click Me</a> <div> <button id="submit">Change Anchor Text</button> </div> </body> </html> |
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
|
1 2 3 4 5 |
$(document).ready(function() { $("#submit").click(function() { $("a").html('Bing it!'); }) }); |
HTML
|
1 2 3 4 5 6 7 8 9 |
<!doctype html> <html lang="en"> <body> <a href="https://www.bing.com/">Click Me</a> <div> <button id="submit">Change Anchor Text</button> </div> </body> </html> |
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
|
1 2 3 4 5 |
$(document).ready(function() { $("#submit").click(function() { document.querySelector('a').text = "Bing it!"; }); }); |
HTML
|
1 2 3 4 5 6 7 8 9 |
<!doctype html> <html lang="en"> <body> <a href="https://www.bing.com/">Click Me</a> <div> <button id="submit">Change Anchor Text</button> </div> </body> </html> |
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
|
1 2 3 4 5 6 |
document.getElementById('submit').onclick = function(e) { var anchors = document.querySelectorAll('a'); anchors.forEach(function(a) { a.text = "Bing it!"; }); } |
HTML
|
1 2 3 4 5 6 7 8 9 |
<!doctype html> <html lang="en"> <body> <a href="https://www.bing.com/">Click Me</a> <div> <button id="submit">Change Anchor Text</button> </div> </body> </html> |
If you want to be more specific, you can use the getElementById() method, which returns the anchor tag matching the specified ID.
JS
|
1 2 3 |
document.getElementById('submit').onclick = function() { document.getElementById("search_link").innerHTML = "Bing it!"; } |
HTML
|
1 2 3 4 5 6 7 8 9 |
<!doctype html> <html lang="en"> <body> <a id="search_link" href="https://www.bing.com/">Click Me</a> <div> <button id="submit">Change Anchor Text</button> </div> </body> </html> |
That’s all about replacing the text of an anchor tag in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)