Which JavaScript framework (prototype, script.aculo.us, Mootools, MochiKit...) has decent CSS rule editing support?
This is abou
The question by Robert Siemer explained:
This is about changing a style rule. I want to have dynamic CSS classes which change.
I wanted to give an answer that better defines the question for the readers who are looking for a similar thing and for the writers who mixed up the issue with updating the style of an element.
I think the first part of the beef is to note that the browsers do allow manipulation of the existing stylesheets, as implied in this comment and analyzed in this answer. For example, the following line modifies padding-top
value from 20px
to 300px
on the third rule in the second stylesheet of the document:
document.styleSheets[1].cssRules[2].style.paddingTop = '300px'
... given index.html
:
Bar
... and style.css
:
html, body { padding: 0; margin: 0 }
body { color: black; }
h1 { color: gray; padding-top: 20px; }
The second part of the beef is how to find rules that match a criterion. The both parts have challenges in compatibility with older browsers, as discussed by the answer. If we forget compatibility issues and focus on how such a framework should roughly work, here is my minimal implementation in vanilla JavaScript.
function forEachCSSRule (iteratee) {
var i, j, crs
for (i = 0; i < document.styleSheets.length; i += 1) {
crs = document.styleSheets[i].cssRules
for (j = 0; j < crs.lenght; j += 1) {
iteratee(crs[j])
}
}
}
function getCSSRulesBySelector (selectorString) {
var matched = []
forEachCSSRule(function (cr) {
if (cr.selectorText.includes(selectorString)) {
matched.push(cr)
}
})
return matched
}
function getCSSRulesByStyle (styleString) {
var matched = []
forEachCSSRule(function (cr) {
if (cr.cssText.includes(styleString)) {
matched.push(cr)
}
})
return matched
}
With such a framework you can for example:
var rules = getCSSRulesByStyle('display: none')
rules.forEach(function (rule) {
rule.style.display = 'block'
})
... which is something the original question requested.