I know I can set a CSS value through JavaScript such as:
document.getElementById(\'image_1\').style.top = \'100px\';
But, can I
The cross-browser solution without DOM manipulation given above does not work because it gives the first matching rule, not the last. The last matching rule is the one which applies. Here is a working version:
function getStyleRuleValue(style, selector) {
let value = null;
for (let i = 0; i < document.styleSheets.length; i++) {
const mysheet = document.styleSheets[i];
const myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
for (let j = 0; j < myrules.length; j++) {
if (myrules[j].selectorText &&
myrules[j].selectorText.toLowerCase() === selector) {
value = myrules[j].style[style];
}
}
}
return value;
}
However, this simple search will not work in case of complex selectors.