0

Whenever I use this type of code for javascript to fond the background color of an element, it always returns "".

<style><!--From external stylesheet-->
    #divexample{
        background-color:#4345C7;
    }
</style>

<div id="divexample"></div>

<script type="text/javascript">
    var bgColor=document.getElementById("divexample").style.backgroundColor;
    alert(bgColor);
</script>
2
  • Are your styles loaded before the JS?
    – Shomz
    Sep 28, 2014 at 0:44
  • 1
    Check on MSDN.
    – The Alpha
    Sep 28, 2014 at 0:50

2 Answers 2

0

You might want to consider using jQuery. You could then easily get the backgroundColor:

var bgColor = $("#divexample").css("backgroundColor");
0

Check this:

http://jsfiddle.net/h28zdhtc/4/

 <style>
  div {
    width: 60px;
    height: 60px;
    margin: 5px;
    float:left;
  }
  div.div1{background-color:blue;}
 div.div2{background-color:black;}
 div.div3{background-color:green;}
 div.div4{background-color:red;}
 </style>

<span id="result">&nbsp;</span>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
<div class="div4"></div>

<script>
$( "div" ).click(function() {
  var color = $( this ).css( "background-color" );
  $( "#result" ).html( "That div is <span style='color:" +
    color + ";'>" + color + "</span>." );
});
</script>

For more detail see this:

http://api.jquery.com/css/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.