Remove Links Without Losing Their Text

Remove Links Without Losing Their Text

Removing an anchor also removes its visible label. To preserve a school notice's words while removing the link behavior, replace the anchor with a text node containing its label. Work within a chosen container.

Before this topic, review Update Text and Attributes if its terms are unfamiliar.

What you’ll learn

  • Explain remove links without losing their text through the school example.
  • Trace the shown operations and distinguish their result from displayed output.
  • Make the practice change and explain its consequence: The replacement node preserves the edited label as ordinary text.

Work through the school example

This is JavaScript in a browser. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.

Create this markup in a separate index.html, then place the JavaScript in a script after these elements. Use this isolated practice page so the selectors refer to its markup.

<p id="notice">Read <a href="/javascript/">school guide</a>.</p>

JavaScript · browser · complete script for the supplied markup

for (const link of document.querySelectorAll("#notice a")) link.replaceWith(document.createTextNode(link.textContent));
console.log(document.querySelector("#notice").textContent);

Expected output

Read school guide.

Introduction

In web development, you might come across scenarios where you need to dynamically remove all links (anchor tags) from a webpage. Whether you're cleaning up scraped content, enforcing navigation restrictions, or simply experimenting, JavaScript offers several ways to do this efficiently using the DOM (Document Object Model).

What Is a Link in HTML?

A link or anchor in HTML is represented by the <a> tag. These elements typically contain an href attribute and allow users to navigate to another page or section.


<a href="https://example.com">Visit Example</a>

Let’s now explore how to remove all such elements using JavaScript.

Method 1: Using querySelectorAll and forEach

Description:

This approach selects all <a> elements and removes them one by one using remove().

document.querySelectorAll('a').forEach(function(link) {
  link.remove();
});

Output:

All anchor tags will be removed from the DOM.

Explanation:

querySelectorAll('a') returns a static NodeList of all anchor elements. The forEach loop then iterates through each link and removes it using link.remove().

Method 2: Using a while loop and getElementsByTagName

Description:

This technique uses the live HTMLCollection from getElementsByTagName, allowing you to continuously remove elements as the list updates.

let links = document.getElementsByTagName('a');
while (links.length > 0) {
  links[0].parentNode.removeChild(links[0]);
}

Output:

All anchor elements are deleted. DOM is free of links.

Explanation:

getElementsByTagName('a') returns a live collection. As you remove links, the collection updates, so always removing the first element (links[0]) is a safe loop condition.

Method 3: Remove only visible or styled links

Description:

In some cases, you might want to remove only links that are visible or styled a certain way.

document.querySelectorAll('a').forEach(function(link) {
  const style = window.getComputedStyle(link);
  if (style.display !== 'none' && style.visibility !== 'hidden') {
    link.remove();
  }
});

Output:

Only visible links are removed. Hidden links remain untouched.

Bonus: Replace Links with Plain Text

Description:

Instead of removing the link entirely, you might want to keep its text content.

document.querySelectorAll('a').forEach(function(link) {
  const textNode = document.createTextNode(link.textContent);
  link.parentNode.replaceChild(textNode, link);
});

Output:

Links are replaced with plain text. No clickable elements remain.

Why Might You Need This?

  • To sanitize user-generated content
  • For print-friendly pages (no need for navigation)
  • To prevent outbound link tracking
  • To dynamically update sections without affecting layout flow

Conclusion

Removing all links from a document with JavaScript is straightforward once you understand how the DOM works. By leveraging methods like querySelectorAll, getElementsByTagName, and conditional removal, you can tailor the process to suit various needs.

Explore these methods to see which best fits your use case, and remember—DOM manipulation is a powerful tool, so use it wisely!

Recognize the important boundary

This removes links only inside notice. textContent does not preserve nested formatting; use a deliberate child-node transfer if that formatting matters.

Try a small variation

JavaScript · original source for practice

for (const link of document.querySelectorAll("#notice a")) link.replaceWith(document.createTextNode(link.textContent));
console.log(document.querySelector("#notice").textContent);

Your task: Replace school guide with class guide. Predict the result before running the edited program.

The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.

Markup used by this section:

<p id="notice">Read <a href="/javascript/">school guide</a>.</p>

Worked answer and reasoning

The replacement node preserves the edited label as ordinary text.

Markup for this edited program:

<p id="notice">Read <a href="/javascript/">class guide</a>.</p>

JavaScript · complete worked variation

for (const link of document.querySelectorAll("#notice a")) link.replaceWith(document.createTextNode(link.textContent));
console.log(document.querySelector("#notice").textContent);

Expected output

Read class guide.

Predict the original program

JavaScript · original program for this question

for (const link of document.querySelectorAll("#notice a")) link.replaceWith(document.createTextNode(link.textContent));
console.log(document.querySelector("#notice").textContent);

Markup used by this section:

<p id="notice">Read <a href="/javascript/">school guide</a>.</p>
In the browser, what does the original JavaScript example display, in order?
Choose one answer. You can try again.

Answer and explanation

Read school guide.

Removing an anchor also removes its visible label. To preserve a school notice's words while removing the link behavior, replace the anchor with a text node containing its label. Work within a chosen container. This removes links only inside notice. textContent does not preserve nested formatting; use a deliberate child-node transfer if that formatting matters.

Keep the useful idea

Removing an anchor also removes its visible label. To preserve a school notice's words while removing the link behavior, replace the anchor with a text node containing its label. Work within a chosen container.

Check your variation against this explanation: The replacement node preserves the edited label as ordinary text.

Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Respond to an Event →