Select the text in :: before or :: after the pseudo-element

Check out 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 beginning of each <P> and does it as follows

enter image description here

If you use the mouse to select text (to insert a copy), you can select the source text, but not the text before or Aftter added by css.

enter image description here

I have a very specific requirement when I need to allow users to select with mosue in front of the text. How do you do this?

+5
source share
3 answers

You cannot, before and after pseudo classes should not be used for this purpose.

+4
source

How to hack, if you need to copy / paste pseudo elements, you can export the page to PDF and copy it. For example, in Chrome, you can copy the contents of a page from a preview.

+4
source

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

Do not use ::before or ::after , use HTML.

You can use JavaScript to insert it (if that helps):

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

Thus, the text itself is present in the DOM, in contrast to the generated content from CSS.

+1
source

Source: https://habr.com/ru/post/1208708/


All Articles