Why doesn't document.querySelector work on a pseudo-element?

I play with pseudo-elements and javascript, but some how I can not style it with 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>
Run code

Does anyone know why this is not working?

+4
source share
1 answer

If you want to style pseudo elements from javascript, you must use CSSOM to introduce rules. It is not trivial, but it is possible.

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

slightly modified example from this article

CCSOM Link

+5
source

All Articles