Marcus Harrison Marcus Harrison - 1 month ago 12
HTML Question

Is it possible, in Javascript, to add a style property twice to an element?

Given a HTML Element object, is it possible to add the same style property twice to it without having to resort to string manipulation?

Consider the following examples:

<div style="width: 90%; width: calc(100% - 5em);"></div>
<h1 style="font-weight: bold; font-weight: 800;"></h1>
<p style="color: #cccccc; color: rgba(255, 255, 255, 0.8);"></p>


As far as I can tell, setting styles through the
.style
property (e.g.
element.style.color = "blue"
) or the
.style.setProperty
method (e.g.
element.style.setProperty("color", "blue")
) overwrites existing style properties instead of appending them.

Having multiple definitions of the same property allows us to take advantage of the cascading nature of CSS, letting us use more modern CSS property values when they're available while gracefully falling back to "good-enough" values where more recent additions are not supported. However, the only way I can see to do something like this is through manual string manipulation.

Answer

What you want to do is not possible unless you use some custom javascript function.

I guess this is because of the way CSS cascading works.

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. When specificity is equal to any of the multiple declarations, the last declaration found in the CSS is applied to the element. Specificity only applies when the same element is targeted by multiple declarations. Source: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

So when you add the same property twice in the style attribute, the second one will be applied due to specificity. Knowing this the 'logical' behaviour for Javascript when you set properties with .style.setProperty("propertyName", "propertyValue") or element.style.propertyName = "propertyValue". is to overwrite the same property if it already exists, instead of adding a new one.

Comments