0

I have an image:

<a href="https://newlink”.com target="_blank"><img src="https://example.com/assets/images/1.png" /></a>

I want to be able to change the image url href and image src from the css

I could do this for normal text using:

.toBeReplacedDescription span {
    display: none;
}

.toBeReplacedDescription:after {
    content: “Here is the new replaced text.”;
}

But now I want to be able to do it for an image,

Thanks

Peter5
  • 1
  • 1
    Can you explain what your specific scenario is? Meaning why are you trying to do this and why are you trying to accomplish it via CSS (as opposed to just changing your markup)? This is not possible in the way you have phrased it in your question, but your requirements might be able to be met by other workarounds. – Alexander Nied Jan 28 '21 at 19:55
  • An image that is put on multiple pages with the same code snippet. This snippet can then be changed which will update the snippet on all the pages it is on from the centralized css location. – Peter5 Jan 28 '21 at 20:01
  • @Peter5 if the snippet can be changed it makes more sense for you to use a function which takes a parameter with the URL for the new image, and then re-renders the HTML dynamically, you can even add a nice loader to the image if the change is based on user interaction. – AGE Jan 28 '21 at 20:30
  • "change the image url href and image src" — do you mean you want to change the value of the _anchor_ href attribute in the ` – Stephen P Jan 28 '21 at 20:58

2 Answers2

0

You can achieve this using the URL function, make sure to mind browser compatibility if needed.

.toBeReplacedDescription span {
    display: none;
}
    
.toBeReplacedDescription:after {
    content: url(“Here is the new replaced text.”);
}
<a href="https://newlink”.com target="_blank">
    <img src="https://example.com/assets/images/1.png" />
</a>
TheEagle
  • 5,808
  • 3
  • 11
  • 39
AGE
  • 3,752
  • 3
  • 38
  • 60
0

Clicking on the link causes it to swap its background-image. Have fun.

function changeHref(){
var c = document.getElementById('anchor');
c.setAttribute('href','https://stackoverflow.com/');
}
    body{
       font-size: 50pt;
       background-color: #000000;
    } 
    .tobereplaced {
          background-image: url("https://appharbor.com/assets/images/stackoverflow-logo.png");
          background-color: #cccccc;
          background-size: 300px 100px;
        }
    .tobereplaced:focus {
background-image: url("https://logos-download.com/wp-content/uploads/2019/01/Stack_Overflow_Logo.png");
        }
<!DOCTYPE html>
        <html>
        <head>
        <link rel="stylesheet" href="styles.css">
        </head>
        <body>
        <a href="#anchor" id="anchor" class="tobereplaced" >This is a replacement text for anyone</a>
        <button onclick="changeHref()">This changes the Link</button>
        </body>
        </html>
FunnyO
  • 383
  • 2
  • 20