This is difficult to do correctly :( and I believe that a 100% correct result in all cases is impossible.
background-color is not inherited. getComputedStyle returns only what is in the .style.backgroundColor element, if any, or otherwise, what comes from the loaded CSS styles. If these two values ββdo not yet return a value, it returns rgba(0, 0, 0, 0) , in which case you need to climb into the DOM to find out what elements they have. And this is even more complicated in the case of frames that can get their background from the (i.e., top) frame behind them.
Here is an attempt:
const getCbgcolor = (elem) => { if (!getCbgcolor.top) getCbgcolor.top= (() => { try { return window.top.document.documentElement; } catch(e) { return null; }})() }); while (true) { let cbg=window.getComputedStyle(elem).getPropertyValue('background-color'); if (cbg && cbg!='rgba(0, 0, 0, 0)' && cbg!='transparent') return cbg; if (elem===getCbgcolor.top) return 'initial'; elem = elem.parentElement; if (!elem) return ''; } }
(The problems with this is that if someone explicitly set the background of the element to rgba(0, 0, 0, 0) in the style of the element or in the CSS stylesheet, you may want this value instead of a computed value that will not work with this code.)
kofifus
source share