0

I have table cell which has class "cellActive". Which has following defination

.cellActive{background:"#DDDDDD"}

Now i am trying to read the background color property for the cell and it comes null/"".

var bgColor = cell.style.backgroundColor; // returning ""

Is that something mistake on my part of its by behavior. If CSS class is assigning CSS to element can't we read its value in JS ? Does this mean that if we are not assigning property directly to the element we cant get it if in case its inheriting it ?

Anil Namde
  • 6,452
  • 11
  • 63
  • 100
  • 1
    how do you get to `cell` variable? – Sarfraz May 31 '10 at 12:53
  • i am iterating elements by rows something like this, var rows = getElementById('table_id').getElementsByTagName('tr') for(var i=0;............) rows[i].getElementsByTagName('td') – Anil Namde May 31 '10 at 12:58

3 Answers3

3

The style attribute contains only explicitly set properties, not those inherited from a class. You need the so-called "computed style" that reflects the properties the way they were actually rendered.

See the accepted answer to this question for a very good cross-browser solution.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
2

There is a difference between "background" and "background-color". Also, the "style" property means the style property of the element has been set in either HTMl or Javascript. Use "computedStyle" for other cases. That means using the getComputedStyle() method, which you can learn about here.

Robusto
  • 31,447
  • 8
  • 56
  • 77
  • agree but background facilitates to provide more than one background property right ? – Anil Namde May 31 '10 at 12:56
  • 1
    The difference between `background` and `background-color` won't make a difference here, as both would be computed into the `backgroundColor` property. – Pekka May 31 '10 at 12:56
1

there are various ways to access CSS in JavaScript Element.style actually accesses what is written to the style attribute. to get the full CSS rather use getComputedStyle().

Community
  • 1
  • 1
Dormilich
  • 927
  • 5
  • 11