Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'getPropertyPriority' doesn't work when getting styles with 'getComputedStyle'

Tags:

javascript

css

I want to get a dom style to increase the priority.

'CSSStyleDeclaration' has a 'getPropertyPriority' method and there is a problem with its return value. In the example below, when I get 'background', it returns empty, I want to get 'important'

The value obtained with 'styleSheets' is normal, but I don't want to use the loop to find the corresponding selector, I hope to give me a simple solution.

This is the document link

// log is '', I want to get 'important'
console.log(window.getComputedStyle(document.getElementById('box')).getPropertyPriority('background'));
// log is 'important'
console.log(document.styleSheets[0].cssRules[0].style.getPropertyPriority('background'));
// log is 'important'
console.log(document.getElementById('box').style.getPropertyPriority('width'));
#box {
  height: 100px;
  background: black !important;
}
<div id="box" style="width: 100px !important;"></div>
like image 836
Yulin Han Avatar asked Dec 05 '25 08:12

Yulin Han


1 Answers

The CSSStyleDeclaration object returned by getComputedStyleStyle is a bit different than the ones you'll get from say a StyleSheet or an Element's style property.

First this object is read-only, you can't use setProperty on it.

const comp = getComputedStyle(test);
comp.setProperty('backgroundColor', 'green');
<div id="test" style="height:25px;background-color:red"></div>

Then, at getting of its properties it will return the computed value of that property, which is not the same as the one that has been authored:

const comp = getComputedStyle(test);
console.log('computed', comp.getPropertyValue('width'));

const auth = test.style;
console.log('from style', auth.getPropertyValue('width'));
<div id="test" style="width:calc(3% + 25px)"></div>

And since this CSSStyleDeclaration dictionary only holds the computed properties, there is no need for any importance, since these properties will always be alone, and hence, getPropertyPriority will always return the empty string.

To retrieve the original rule that did set this property is often impossible, it could very well come from a cross-domain StyleSheet that you can't read from. And even the incoming CSSTypedOM which does give us a mean to retrieve the authored units and values doesn't expose the property importance.

like image 115
Kaiido Avatar answered Dec 06 '25 22:12

Kaiido



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!