Vishu238
Vishu238

Reputation: 673

Let user select pseudo element using mouse

Hello I have a html page which uses Pseudo element We have set a selection class on the element to set background color red.

div:after {
  content: " Me too !";
  position: absolute;
}
::selection {
  background: red;
}
<div>Select Me.</div>

Please suggest how to make pseudo element selectable.

I can not change the current structure.

Upvotes: 1

Views: 690

Answers (1)

rpdasilva
rpdasilva

Reputation: 41

Short answer is that you cannot "select" a pseudo-element.

Long answer is you can fake it a bit by checking to see if a user has selected text in your div something like:

var element = document.querySelector('div');
var elementText = element.innerText || element.textContent;

element.addEventListener('onmouseup', function() {
  var selectedText;
  var afterText;

  if (window.getSelection) {
    selectedText = window.getSelection().toString();
  } else if (document.selection && document.selection.type === "Text") {
    selectedText = document.selection.createRange().text;
  }

  if (selectedText === elementText) {
    // We've selected the div's text!
  } 
});

Then depending on how you want the behaviour to be, you could add a class to the element to style the ::after element differently, and then append the after element's content to the user selection via:

var afterText = window.getComputedStyle(element, ':after').content;

Upvotes: 4

Related Questions