8

I am playing with pseudo elements and javascript but some how i can not style it using javascript.

    var div = document.querySelector(":before");
    div.style["display"] ="none";
div{
    width:200px;
    height:200px;
    background:red;
    position:relative;
}

div:before{
    position:absolute;
    content:'';
    top:0;
    right:-100px;
    width:100px;
    height:100%;
    background:green;
}
<div></div>

do anyone knows why this is not working?

Gildas.Tambo
  • 22,173
  • 7
  • 50
  • 78
  • 4
    Pseudo elements are not part of the content. They don't have any existence in DOM so you basicly can't manipulate something that doesn't exist – user28470 Sep 29 '14 at 08:05
  • 7
    CSS Pseudo-classes will never return any elements, as specified in the Selectors API http://www.w3.org/TR/selectors-api/#grammar – ale Sep 29 '14 at 08:07
  • 3
    Unfortunately you can only create pseudo elements (shadow elements) with `.createShadowRoot()` but you cannot access them. – Derek 朕會功夫 Sep 29 '14 at 08:14
  • The answer here (https://stackoverflow.com/questions/49106088/changing-pseudo-element-style-from-javascript) shows how you can use document.querySelector, just change the pseudo element to a span (if possible) – plugincontainer Jun 21 '19 at 14:38

1 Answers1

10

If you want to style pseudo elements from javascript you have to use the CSSOM to inject the rules. It's not trivial, but it's possible.

var sheet = document.styleSheets[0]; //get style sheet somehow
var rules = sheet.rules; 
sheet.insertRule('div:before { display: none; }', rules.length);

a slightly modified example from this article

CCSOM Reference

Winchestro
  • 2,138
  • 14
  • 18