What is the CSS specificity when Javascript modifies CSS?
Such as:
document.getElementById("demo").style.color = "red";
Is it considered inline styling?
What is the CSS specificity when Javascript modifies CSS?
Such as:
document.getElementById("demo").style.color = "red";
Is it considered inline styling?
CSS specificity when Javascript modifies CSS?
Exactly the same as if you modified the CSS by editing the original source code instead of using JS.
document.getElementById("demo").style.color = "red";
In this case, you are modifying the styles attached directly to the element.
<div id="demo" style="color: red">
So maximum specificity. (count 1 if the declaration is from is a 'style' attribute rather than a rule with a selector)
If you had used JS to modify a ruleset, then the specificity would be different.
The style
property on DOM nodes is essentially an accessor/mutator for the style
attribute for those DOM nodes.
For purposes of this answer consider node.style.color = 'red'
to be equivalent to node.setAttribute(node.getAttribute('style') + ' color: red')
*.
With that the question can be reframed as
What is the CSS specificity of rules in a
style
attribute?
So of course the answer is that the spec defines this behavior
A selector's specificity is calculated as follows:
...
Note: the specificity of the styles specified in an HTML style attribute is described in CSS 2.1. [CSS21].
Yo dawg, I heard you liked specs
A selector's specificity is calculated as follows:
- count 1 if the declaration is from is a 'style' attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element's "style" attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)
- count the number of ID attributes in the selector (= b)
- count the number of other attributes and pseudo-classes in the selector (= c)
- count the number of element names and pseudo-elements in the selector (= d)
emphasis mine
So the actual calculated specificity of document.getElementById("demo").style.color = "red";
is 1,0,0,0
* This is of course ignoring existing rules within style
.
Through JavaScript you are modifying the DOM tree ( Html File ) not the CSS file, hence it is inline styling.
Generally inline styling in this way is not frowned upon as inline styling on a static HTML document.