Get the background color of a DIV doesn't work


I don't understand where's the problem. The following code displays background color of DIV2 but not the one of DIV1. Please try it.
	#div1{ background-color:#333333}
<div id="div1" >asdf</div>
<div id="div2" style="background-color:#666666">asdf</div>
  window.onload= function(){
    var color1 = document.getElementById("div1").style.backgroundColor;
    var color2 = document.getElementById("div2").style.backgroundColor;

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Albert Van HalenAnalyst developerCommented:
Úse this code
function getStyle(el, styleProp)
	if (el.currentStyle)
		return el.currentStyle[styleProp];
	else if (window.getComputedStyle)
		return document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
var color1 = getStyle(document.getElementById("div1"), "backgroundColor");
var color2 = getStyle(document.getElementById("div2"), "backgroundColor");

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
When you type 'document.getElementById("div1")' your're sucking the div1 element from the DOM tree of the html document, its style property only gives you the "inline style" - what is specified in the style attribute, not the css sheet.

You can access the actual style being applied to the element, rather than the inline style for an element with the following code on most browsers:

var color1 = window.getComputedStyle(document.getElementById("div1"),null).backgroundColor;

It won't work on IE though, so try this instead (not 100% certain about this one) if you're using that:

var color1 = window.getCurrentStyle(document.getElementById("div1"),'background-color');

maya75Author Commented:
Thanks AlbertVanHalen, it works perfect in IE. Do you know if it's possible to do it in Firefox ?
maya75Author Commented:
Thanks both of you, the first comment works for IE and the second for Firefox.

Thanks again !
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Languages and Standards

From novice to tech pro — start learning today.