Bansoa is the answer Bansoa is the answer - 1 month ago 6
Javascript Question

Why is document.querySelector not working on pseudo element?

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?

Answer

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