3

How should I do this in Javascript?

// CSS
*::-moz-selection{
 background:transparent; 
}

I tried these but doesn't really works:

// Javascript
document.mozSelection = "transparent";
document.body.mozSelection = "transparent";
Charles Sprayberry
  • 7,741
  • 3
  • 41
  • 50
Adam Halasz
  • 57,421
  • 66
  • 149
  • 213

2 Answers2

5

You can add a rule to the stylesheet.

// Get the first stylesheet 
var ssheet = document.styleSheets[0];

if ("insertRule" in ss) {
    ss.insertRule('#yourdivcontainer::-moz-selection { background: transparent; }', 0);        
}

IMO, it's not a good practice anyway. You should create a CSS class with the selection color and change the class itself via JS instead of the style.

Soufiane Hassou
  • 17,257
  • 2
  • 39
  • 75
2

:: selectors are for pseudo-elements, CSS objects that don't correspond to actual element nodes. Because there is no element node to match ::-moz-selection, you can't style it directly on an element's .style.background property.

Instead you would have to insert a new stylesheet rule duplicating the above CSS (see this question for a couple of methods of doing that).

Community
  • 1
  • 1
bobince
  • 528,062
  • 107
  • 651
  • 834