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.
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'
.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With