0

I want to visually replace parts of a string, but when I select/copy the string the original text should be copied.

I came across this answer https://stackoverflow.com/a/67356640/6567275 and CSS content seemed perfect for this, but it doesn't stick.

[data-replace] {
  content: attr(data-replace);
  background: yellow;
}

.replace {
  content: "test";
  background: orange;
}

.replace-with-image {
  content: url("//cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico");
  background: green;
}
<p>
  foo <span data-replace="test">bar</span> baz.<br>
  foo <span class="replace">bar</span> baz.<br>
  foo <span class="replace-with-image">bar</span> baz.<br>
</p>

This should show "foo test baz." on the screen, <br>
but when I select/copy it it should copy as "foo bar baz."

I know ::before and ::after, but that's not what I'm talking about. According to MDN the CSS content property applies to "All elements, tree-abiding pseudo-elements, and page margin boxes" and according to caniuse this feature is available for several years across browsers.

I tried it in Chrome, Opera, Firefox and Edge.

Do I misunderstand something? Or am I doing something wrong?

Why doesn't this work?

Edit: replace element content with an image works :D

Thomas
  • 11,958
  • 1
  • 14
  • 23
  • 1
    Unless I'm reading it incorrectly, if you specify a string for the content of a non-psuedo element, then you're specifying "the 'alt text' for the element.", not setting replacement content. According to [W3](https://www.w3.org/TR/css-content-3/#:~:text=The%20content%20property%20dictates%20what,boxes%2C%20it%20is%20more%20powerful.), _"For elements, it has only one purpose: specifying that the element renders as normal, or replacing the element with an image (and possibly some associated "alt text")."_ – j08691 Feb 06 '23 at 21:41
  • @j08691 I've read the part about the alt-text but didn't get this to work either. But replacing the element with an image works. Thanks for the pointer. – Thomas Feb 06 '23 at 22:19

0 Answers0