I have this HTML page:
document.addEventListener("DOMContentLoaded", function (event) {
var inner_div = document.getElementById("innerDiv");
console.log(getComputedStyle(inner_div, null)["backgroundColor"]);
});
#outterDiv {
background-color: papayawhip;
}
<div id="outterDiv">
<div id="innerDiv">
I am an inner div
</div>
</div>
I want to find out the computed background color of the inner div without having to look into parent(s) element's computed style. Is that possible?
You apparently mean to ask
How do I find the background color for some element which is used by virtue of that color being set as the background color of some ancestor which shows through because all intervening elements having transparent background color?
However, your question is confusing because you are using the word "inherited", which has a very specific meaning in CSS, which is not relevant here.
The background-color
property is not inherited in the CSS sense. Every element has its own background color, which by default is transparent
.
The reason that you inner div looks like it has a papayawhip background is that actually it has a transparent background, which lets the papayawhip background of the outer div show through. There is nothing about the inner div that knows or cares about papayawhip, or that can be queried to return papayawhip.
The only way to find that the inner div is going to have a papayawhip background is to traverse the DOM tree and find the closest parent that has a non-transparent background color. This is explained in the question proposed as a dup target.
By the way, what is your underlying problem here? Why are you trying to do this? There are probably better ways.
add background-color: inherit;
to your #innerDiv
document.addEventListener("DOMContentLoaded", function (event) {
var inner_div = document.getElementById("innerDiv");
console.log(getComputedStyle(inner_div, null)["backgroundColor"]);
});
#outterDiv {
background-color: papayawhip;
}
#innerDiv {
background-color: inherit;
}
<div id="outterDiv">
<div id="innerDiv">
I am an inner div
</div>
</div>