title: Getting the real background-color of an element?
body: <p>Currently I want to get the <strong>real</strong> background-color of a specified object, here, the <strong>real</strong> means what the people see, for instance, given the following code:</p>
  <pre class="lang-html prettyprint-override"><code>&lt;div id=&quot;foo&quot; style=&quot;background-color: red&quot;&gt;
      I am red
      &lt;span id=&quot;bar&quot;&gt;
           I have no background, but I am red
      &lt;/span&gt;
  &lt;/div&gt;
  </code></pre>
  <p>The real background-color of <code>#bar</code> should be <code>rbg(255,0,0)</code>.</p>
  <p>Here's what I have so far:</p>
  <pre class="lang-js prettyprint-override"><code>function color_visible(color_str) {
    return color_str &amp;&amp; !(color_str.substr(0, 4) == &quot;rgba&quot; &amp;&amp; color_str.substr(-2, 2) == &quot;0)&quot;);
  }
  
  function get_bgcolor (obj) {
    var ret = $(obj).css(&quot;background-color&quot;);
    if (!color_visible(ret)) ret = $(obj).css(&quot;bgcolor&quot;);
    if (color_visible(ret)) return ret;
    if (!$(obj).is(&quot;body&quot;)) return get_bgcolor($(obj).parent());
    return &quot;rgb(255, 255, 255)&quot;;
  }
  </code></pre>
  <p>But is there a better way to do it?</p>
  <h3>Demo in Stack Snippet and <a href="http://jsfiddle.net/bRPQU/" rel="noreferrer">jsFiddle</a></h3>
  <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
  <div class="snippet-code snippet-currently-hidden">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function color_visible(color_str) {
    return color_str &amp;&amp; !(color_str.substr(0, 4) == "rgba" &amp;&amp; color_str.substr(-2, 2) == "0)");
  }
  
  function get_bgcolor (obj) {
    var ret = $(obj).css("background-color");
    if (!color_visible(ret)) ret = $(obj).css("bgcolor");
    if (color_visible(ret)) return ret;
    if (!$(obj).is("body")) return get_bgcolor($(obj).parent());
    return "rgb(255, 255, 255)";
  }
  
  console.log(get_bgcolor($("#bar")));
  console.log(get_bgcolor($("#baz")));
  console.log(get_bgcolor($("#foo")));
  console.log(get_bgcolor($("body")));</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background-color: yellow;
  }
  
  .bg_white {
    background-color: #FFF;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;div&gt;
    &lt;div id="foo" style="background-color: red"&gt;
      I am red
      &lt;span id="bar"&gt;
        I have no background
      &lt;/span&gt;
  
      &lt;span id="baz" class="bg_white"&gt;
        I am white
      &lt;/span&gt;
    &lt;/div&gt;
    I am yellow
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>