JavaScript Code

How to change text of link element using JavaScript?

Tutorials using JS

Change text of link element

Given a link element in the document, change text of link element using JavaScript.


To change the text of a link element in the document using JavaScript, select the link element by the required selection criteria, and use Element.textContent property. Set textContent property for the link element with the required text.

const link = document.getElementById("link1");
link.textContent = "An updated link"; 


In the following HTML code, we have a button element and a link element. When user clicks on the button, we change the text in the link element to 'New link'.

<!DOCTYPE html>
<h1>JavaScript Tutorial</h1>
<h2>Update text in link element</h2>
<button id="myBtn">Click me</button><br>
<a id="link1" href="/a-link/">Old Link</a><br>

//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
    //get all the links in the document
    const link = document.getElementById("link1");
    link.textContent = "New link";


Copyright @2022