๐งจ NoModificationAllowedError: Failed to set the 'padding-left' property on 'CSSStyleDeclaration': These styles are computed, and therefore the 'padding-left' property is read-only.
// โญ๏ธ elem.styleProp(prop[,val])
// get:
// elem.styleProp('padding-left')
// = elem.styleProp('paddingLeft')
// = getComputedStyle(elem).paddingLeft
// โ elem.style.paddingLeft โ๏ธ
// set:
// elem.styleProp('padding-left', '8px')
// = elem.styleProp('paddingLeft', '8px')
// = elem.style.paddingLeft = '8px'
Element.prototype.styleProp = function(prop, val=undefined){
const camelCase = !prop.includes('-');
// set prop if necessary
// โญ๏ธ Note:
// getComputedStyle() is read-only, DO NOT use it to set new value,
// use `this.style` insteadโ๏ธ
if (val) {
if (camelCase) this.style[prop] = val;
else this.style.setProperty(prop, val); // kebab case
}
// return prop
const style = getComputedStyle(this);
return camelCase ? style[prop] : style.getPropertyValue(prop);
};
// โญ๏ธ elem.styleProp(prop[,val])
// get:
// elem.styleProp('padding-left')
// = elem.styleProp('paddingLeft')
// = getComputedStyle(elem).paddingLeft
// โ elem.style.paddingLeft โ๏ธ
// set:
// elem.styleProp('padding-left', '8px')
// = elem.styleProp('paddingLeft', '8px')
// = elem.style.paddingLeft = '8px'
function styleProp(elem, prop, val=undefined){
const camelCase = !prop.includes('-');
// set prop if necessary
// โญ๏ธ Note:
// getComputedStyle() is read-only, DO NOT use it to set new value,
// use `this.style` insteadโ๏ธ
if (val) {
if (camelCase) elem.style[prop] = val;
else elem.style.setProperty(prop, val); // kebab case
}
// return prop
const style = getComputedStyle(elem);
return camelCase ? style[prop] : style.getPropertyValue(prop);
};
CSSStyleDeclaration โฉ
window.getComputedStyle(elem);
window.getComputedStyle(elem, pseudoElem);
// style get/set property
var value = style.getPropertyValue(prop);
style.setProperty(prop, value, priority);
JS.info โฉ
Window โฉ .() - returns an object (live object) containing the values of all CSS properties of an element.