Select text in ::before or ::after pseudo-element
Asked Answered
C

4

27

Look this very simple code

<!DOCTYPE html>
<html>
<head>
<style>
p::before {
    content: "Before - ";
}
</style>
</head>
<body>
<p>Hello</p>
<p>Bye</p>   
</body>
</html>

Css adds ¨Before -" at the start of every <P> and renders like this

enter image description here

If you use your mouse to select the text (for copy paste) you can select the original text, but not the Before or Aftter text added by css.

enter image description here

I have a very specific requirement where I need to allow users to select with the mosue the Before text. How would you do it?

Candler answered 10/12, 2014 at 2:7 Comment(2)
No you can't. That's what the phrase "pseudo" means.Judah
Asked and answered, more than once. See Is it possible to select css generated content?Elijaheliminate
S
14

You can't, the before and after pseudo classes are not meant to be used for that purpose.

Shaia answered 10/12, 2014 at 2:14 Comment(0)
P
17

This cannot be done within an HTML page, but as a hack, if you need to copy/paste pseudo elements, you can export the page to PDF and copy from it. In Chrome, for example, you can copy page's content from print preview.

Padauk answered 20/3, 2015 at 11:29 Comment(0)
S
14

You can't, the before and after pseudo classes are not meant to be used for that purpose.

Shaia answered 10/12, 2014 at 2:14 Comment(0)
R
4

If users need to select the generated text, it should be considered content (and in the HTML), not presentation (and hidden in the CSS).

Don't use ::before or ::after, use HTML.

You could use JavaScript to insert it (if that would help):

var text = document.createTextNode('Before - ');
Array.prototype.forEach.call(document.getElementsByTagName('p'), function (p) {
    p.insertBefore(text.cloneNode(), p.firstChild);
});

This way the text itself is present in the DOM, unlike generated content from CSS.

Reid answered 10/12, 2014 at 2:14 Comment(2)
Sadly I need the word outside the DOM. If is present in the HTML it breaks another features of the website.Candler
Calling something which breaks if some word is present in the DOM a "feature" is being quite generous.Elijaheliminate
V
0

It appears CSS-added content like ::before or ::after content or quotes (for a <q> element) and the content added by other pseudo-elements like ::marker is non-selectable because browser-wise, a selection begins and ends somewhere in the DOM, whereas CSS-added content is not part of the DOM.

For that reason, to my great disappointment, even the user-select CSS property does not allow the user to select ::before or ::after contents.

Val answered 24/7, 2024 at 14:36 Comment(1)
Please, edit and try for How to Answer, edit and try for How to Answer. Please avoid the impression to ask a question instead of answering. You can e.g. phrase a conditional answer like "If your problem is ... then the solution is ... because ... ."Sung

© 2022 - 2025 — McMap. All rights reserved.