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?

2

3 Answers 3

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.

0
14

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

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.

2
  • Sadly I need the word outside the DOM. If is present in the HTML it breaks another features of the website. Dec 10, 2014 at 2:25
  • 7
    Calling something which breaks if some word is present in the DOM a "feature" is being quite generous.
    – user663031
    Dec 10, 2014 at 3:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.