0

I want to get the background property of my element. This is my code.

<!doctype html>
<html>
<head>
<style>
div#pt {
    background: rgba(192,15,18,1.00);
    width: 200px;
    height: 200px;
}
</style>
</head>

<body>
<div id="pt" onClick="pick()"></div>
<script>
function pick() {
debugger;
var color = document.getElementById("pt").style.background;
}
</script>
</body>
</html>

I think this will work, but it doesn't work. It gives an empty string to color variable. I think this is not the right way to get the value of background's property. So, kindly help me, how can i get the value of background's property.

Hemant Parihar
  • 732
  • 1
  • 6
  • 19

2 Answers2

2

The style property only contains styles assigned in a style attribute or set by scripting. Styles set in a style element or an external stylesheet won't be found there, at which point you need different techniques for different browsers (standard techniques for everything but IE, as usual).

For IE

var color= document.getElementById("pt").currentStyle.background;

Other Browsers

var color= getComputedStyle(document.getElementById("pt")).getPropertyValue(background);
Vibhesh Kaul
  • 2,593
  • 1
  • 21
  • 38
1

Use the getComputedStyle as a fall back. You can do something like this:

var color =
   (document.getElementById("pt").style.background.length > 0) ?
     document.getElementById("pt").style.background.length : 
     getComputedStyle(document.getElementById("pt")).getPropertyValue("background");

The line breaks are only for illustrative purposes.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252