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.

Solution

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"; 

Program

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>
<html>
<body>
<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>

<script>
//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";
});
</script>

</body>
</html>

Copyright @2022