Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get/Set CSS property values via Javascript: questions

Some things are unclear to me:

var myDiv = document.getElementById("myDiv");
var computedStyle = window.getComputedStyle(myDiv);

1) Isn't it possible to directly get global border color of a div if there is only one color, the same for each side:

computedStyle.getPropertyValue("border-color");

Instead of doing:

computedStyle.getPropertyValue("border-left-color");

OR

computedStyle.getPropertyValue("border-right-color");

OR

computedStyle.getPropertyValue("border-top-color");

...

2) When having style properties in a CSS file, they are only accessible through the getComputedStyle method and not via the style property like style properties defined inline, via a style attribute in the div, I'm right?

myDiv.style.getPropertyValue("border-left-color");

This will not work.

3) If we want to set a style property, we have to use the style attribute of the element, is it not possible using the computed style object?

computedStyle.setProperty("border-color", "yellowgreen", null);

I thought using the style attribute was the "old way to do", like using the inline style attribute or using object.style.property = "value" to set a style property in Javascript.

Thanks.

jsFiddle: http://jsfiddle.net/pgtFR/12/

like image 360
baptx Avatar asked May 20 '12 18:05

baptx


1 Answers

1) Isn't it possible to directly get global border color of a div if there is only one color, the same for each side:

Yes, its possible to get the computed style by just using the shorthand property name. I tried the example you have shared on jsfiddle and computedStyle.getPropertyValue("border-color") does return (265,65,0) which is the rgb code for orange as expected.

2) When having style properties in a CSS file, they are only accessible through the getComputedStyle method and not via the style property like style properties defined inline, via a style attribute in the div, I'm right?

Yes. getComputedStyle returns the final computed style value by the browser after applying external, internal and inline style rules. .style attribute only refers to the inline style for the element.

3) If we want to set a style property, we have to use the style attribute of the element, is it not possible using the computed style object?

No. According to this document, getComputedStyle returns a CSSStyleDeclaration object which is read-only.

like image 69
Jollyjagga Avatar answered Nov 07 '22 00:11

Jollyjagga