JavaScript Code

How to replace links with text using JavaScript?


Tutorials using JS

Replace links with text

Given a HTML document with link elements in it, replace all the link elements with respective link texts, using JavaScript.

Solution

To replace all the link elements in the document with the corresponding link texts using JavaScript, set each of the link’s outerHTML property with the link’s text property.

link.outerHTML = link.text;

Select the link elements by a selector (for example, we can select all the link elements by tag name a), use a while loop to check if there are any more links, and if so replace the first link element with its text.

const links = document.getElementsByTagName("a");
while ( links.length > 0 ) {
    var link = links[0];
    link.outerHTML = link.text;
}

Program

In the following HTML code, we have a button element and two link elements. When user clicks on the button, we delete all the links in the document by calling remove() method on each of the link.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Replace links with text</h2>
<button id="myBtn">Click me</button><br>
<a href="/line-one/">Link 1</a><br>
<a href="/link-two/">Link 2</a>

<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
    const links = document.getElementsByTagName("a");
    while ( links.length > 0 ) {
        var link = links[0];
        link.outerHTML = link.text;
    }
});
</script>

</body>
</html>

Copyright @2022