Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect the inherited background-color of an element using jQuery/JS?

Using jQuery (or just JavaScript), how do I detect the inherited background-color of an element?

For example:

<div style="background-color: red">
    <p id="target">I'd like to know that the background-color here is red</p>
</div>

However:

$('#target').css('background-color') == rgba(0,0,0,0)

and

$('#target').css('backgroundColor') == rgba(0,0,0,0)

I'm asking for a general solution. $('#target').parent().css('background-color') would work in this instance, but not all.

like image 351
David Smith Avatar asked Nov 23 '10 19:11

David Smith


2 Answers

This could be accomplished by using the parent() in a loop until you reach the body tag:

I've set up a quick jsfiddle site with a little demo based on your code.

Edit: Good catch fudgey. After doing some testing it appears that IE7 will return 'transparent' instead of the rgba(0,0,0,0) value. Here's an updated link which I tested in IE7, Chrome 7, and Firefox 3.6.1.2. Another caveat with this approach: Chrome/Firefox will return rgb(255,0,0); IE returned 'red'.

like image 89
3 revs Avatar answered Sep 28 '22 00:09

3 revs


You can make use of window.getComputedStyle() to get the inherited value.

Caveat: You must manually declare the inheritance in css or inline.

#target{
  background-color: inherit;
}

Working example:

let bgc = window.getComputedStyle($('#target')[0],null).getPropertyValue("background-color");
console.log(bgc);
#target{
  background-color: inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style="background-color: red">
    <p id="target">I'd like to know that the background-color here is red</p>
</div>
like image 30
Zze Avatar answered Sep 28 '22 02:09

Zze