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.

3
  • The element.style object contains only inline CSS. Commented Aug 28, 2015 at 9:17
  • 1
    window.getComputedStyle(element); Commented Aug 28, 2015 at 9:18
  • Thank you. I got it. This will make my concept more clear. developer.mozilla.org/en-US/docs/Web/API/Window/… Commented Aug 28, 2015 at 10:08

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

5 Comments

I apply it but it work fine in Chrome, but in rest of the browser (firefox, internet explorer , Microsoft edge) it give an empty string. Big Issue for me.
I've given a solution for IE(internet explorer) an Other browsers separately !
What you suggest for internet explorer is not working.
oh yes check it now check the edit!
Still not working It return me an undefined value.
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.

2 Comments

What does fall back means? I used only this line getComputedStyle(document.getElementById("pt")).getPropertyValue("background"); It works fine in Chrome but not in rest of the browser.
Fallback means, a backup method whne the main method doesn't work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.