This JavaScript function lets you define a CSS selector list, and to output CSS rules with JS interpolation from the context of each element in the document matching the selector.
scoped(selector, rule)
selector
is a CSS selectorrule
is one or more CSS declarations separated by semicolonsInput:
scoped('div', `
margin: 1em;
background: lime;
height: eval(this.offsetWidth / (16/9))px;
`)
Output:
/* Scope: div */
[data-scoped-unique="0"] {
margin: 1em;
background: lime;
height: 144.5625px;
}
function scoped(selector, rule) {
var tag = document.querySelectorAll(selector)
var style = ''
var count = 0
for (var i=0; i < tag.length; i++) {
var attr = selector.replace(/\W+/g, '')
tag[i].setAttribute('data-scoped-' + attr, count)
var scopedRule = rule.replace(/eval\((.*)\)/g, function(string, match){
var func = new Function('return ' + match)
return (func.call(tag[i]) || '')
})
style += '\n/* Scope: ' + selector + ' */\n'
+ '[data-scoped-' + attr + '="' + count + '"] {\n'
+ ' ' + scopedRule + '\n'
+ '}\n'
count++
}
return style
}