Style.backgroundColor is an empty string in JavaScript.

I have the following code below which I am trying to set the background color. However, the background color is returned as an empty string. I'm not sure why ... Does this have anything to do with JavaScript types?

function function1(){ var color = document.getElementById('rg_vw.national_avg').style.backgroundColor; //this below appears as an empty alert at runtime. it an empty string. alert(color) } 

As a health check, if I use the value property, it outputs the correct value for this particular field ... so I'm a little upset as to why backgroundColor is an empty string.

 //this works just fine var value = document.getElementById('rg_vw.national_avg').value alert(value) 
+6
source share
1 answer

If you did not directly define the backgroundColor of the element itself, you should use getComputedStyle() or currentStyle to get the value of the style property.

A method compatible with several browsers will look like this:

 function getStyle(el,styleProp) { if (el.currentStyle) return el.currentStyle[styleProp]; return document.defaultView.getComputedStyle(el,null)[styleProp]; } 

You can see the working jsFiddle example.

Additional Information:

  • For more information on getComputedStyle() see this page .
  • For more information on currentStyle (IE) see this page .
  • For more information on browser compatibility issues, see this page .
+14
source

Source: https://habr.com/ru/post/915519/


All Articles