To change the style of a pseudo-element, you can utilize the CSSRule
in pure JavaScript. The key is to define your selector consistently in the CSS code so that the rule can be found successfully. Once the rule is located, styling can be easily modified. Additionally, new rules can be inserted to apply different styles to elements. Here is an updated demo code based on your specific requirements:
HTML:
<div>Pane 1</div>
<div>Pane 2</div>
<div>Pane 3</div>
CSS:
div {
border:1px solid black;
width:100px;
height:100px;
position:relative;
display:inline-block;
color:white;
}
div:before {
content:'';
position:absolute;
width:100%;
height:100%;
z-index:-1;
background-size:cover;
}
JavaScript:
var divs = document.querySelectorAll('div');
function applyBeforeElementStyleOn(elem, styleProp, styleVal){
if(!elem.beforeElementStyle) {
var sheet = document.styleSheets[0];
var currentTime = new Date();
var guid = (currentTime + "" +
currentTime.getMilliseconds()).replace(/[ :+()]/g,'') +
parseInt(Math.random()*1000);
var ruleText = elem.tagName + "[" + guid + "]:before {}";
sheet.insertRule(ruleText, 0);
elem.beforeElementStyle = (sheet.cssRules || sheet.rules)[0].style;
elem.setAttribute(guid.toLowerCase(),"");
}
elem.beforeElementStyle[styleProp] = styleVal;
}
var data = [
{bg: "url(http://placekitten.com/300/300)", brightness: 0.2},
{bg: "url(http://placekitten.com/100/100)", brightness: 0.9},
{bg: "url(http://placekitten.com/400/400)", brightness: 0.6},
];
for(var i = 0; i < data.length ; i++){
applyBeforeElementStyleOn(divs[i], "background-image", data[i].bg);
applyBeforeElementStyleOn(divs[i], "webkitFilter",
"brightness(" + data[i].brightness + ")");
}