Replacing anchor tag with different text using CSS only

Viewed 3025

I want to replace an anchor tag with some different text using CSS only. I have tried using CSS pseudo elements but using that puts the new text inside the anchor tag which is not intended. I want to replace whole anchor tag, so that new text will not have any links.

Original code:

<a href="www.google.com" class="link-class">The google link</a>
<a href="www.yahoo.com" class="link-class">The yahoo link</a>
<a href="www.so.com">Don't replace this</a>
<a href="www.ddgo.com" class="link-class">The ddgo link</a>

After replacement:

Replacement text
Replacement text
<a href="www.so.com">Don't replace this</a>
Replacement text

I have tried this:

.link-class {
  visibility: hidden;
  position: relative;
}
.link-class:after {
  visibility: visible;
  content: 'Replacement text';
  position: absolute;
  left: 0;
  top: 0;
}
<a href="www.google.com" class="link-class">The google link</a>
    <a href="www.yahoo.com" class="link-class">The yahoo link</a>
    <a href="www.so.com">Don't replace this</a>
    <a href="www.ddgo.com" class="link-class">The ddgo link</a>

In short, I don't want hyperlinks on replaced text, how can I do that with CSS only ?


I am doing this for a particular page through my extension, and the page loads it's DOM content through ajax requests, so using JS for this small tasks in this scenario becomes very cumbersome.

2 Answers

try with this .link-class:after

  pointer-events: none;
  cursor: default;
  text-decoration: none;
  color: black;

.link-class {
  visibility: hidden;
  position: relative;
}

.link-class:after {
  visibility: visible;
  content: 'Replacement text';
  position: absolute;
  left: 0;
  top: 0;
  pointer-events: none;
  cursor: default;
  text-decoration: none;
  color: black;
}
<a href="www.google.com" class="link-class">The google link</a>
<a href="www.yahoo.com" class="link-class">The yahoo link</a>
<a href="www.so.com">Don't replace this</a>
<a href="www.ddgo.com" class="link-class">The ddgo link</a>

Here is a cleaner way to achieve this using CSS only.

.link-class {
  font-size: 0;
  pointer-events: none;
  visibility: hidden;
  text-decoration: none;
  color: inherit;
}

.link-class:after {
  content: 'Replacement text';
  visibility: visible;
  font-size: 16px;
}
<a href="www.google.com" class="link-class">The google link</a>
<a href="www.yahoo.com" class="link-class">The yahoo link</a>
<a href="www.so.com">Don't replace this</a>
<a href="www.ddgo.com" class="link-class">The ddgo link</a>

Related