How to Retrieve an Element’s Final Background-Color with Pure JavaScript
This article explains how to use native JavaScript, including getComputedStyle and custom utility functions, to accurately obtain the computed background-color of any DOM element while handling special cases such as display, opacity, and visibility without relying on libraries.
1. Problem
Use JavaScript to obtain the final background-color of an element on a page, ignoring IE browsers and float scenarios.
2. Problem Analysis
1. Core JavaScript fundamentals Front‑end developers need to master native style retrieval beyond jQuery.
2. Interview assessment Beyond simply fetching computed styles, the task evaluates meticulous thinking and experience, especially handling special values like display, opacity, and visibility.
3. Theoretical Basis
1. Inline styles If an element’s style attribute contains a background-color, it can be read directly (ignoring !important for now).
2. Cascading external styles The DOM2 style specification provides document.defaultView.getComputedStyle(), which returns a read‑only CSSStyleDeclaration containing all computed styles for an element.
4. Solution
4.1 Encapsulate utilities in a WDS (Wall DOM Script) namespace
Encapsulation prevents accidental global pollution.
4.2 Utility method camelize
Converts hyphenated CSS property names to camelCase, e.g., background-color → backgroundColor, facilitating the later getStyle() implementation.
4.3 Retrieve computed style of a specific element
This step satisfies the primary interview requirement and verifies solid JavaScript fundamentals.
Safety checks like if(!elem || !property) and feature detection
if(document.defaultView && document.defaultView.getComputedStyle)demonstrate logical rigor.
4.4 Exclude special cases
4.5 Obtain the element’s final displayed color
The style value is fetched recursively; if a direct value is found, it is returned immediately.
If a special case is triggered, the algorithm climbs to parent nodes to locate the visible background-color, stopping at the html root with a check else if(elem != document.documentElement).
5. Overlooked “Big Bosses”
5.1 The !important rule Misusing !important creates maintenance nightmares; this solution deliberately omits handling it.
5.2 Parent or root nodes with invisible CSS If a parent sets display:none or uses opacity, display, visibility, the logic becomes significantly more complex, which is not covered here.
6. Points for Improvement
The special‑case checks are simplistic; color values like rgb(255,0,0) and named colors such as red are not normalized—only a basic if(value == "transparent" || value == "rgba(0, 0, 0, 0)") check is used.
Further work could explore robust color‑conversion utilities.
7. Source Code and Demo
Source repository:
https://github.com/wall-wxk/blogDemo/blob/master/2017/02/05/getStyle.htmlLive demo:
https://wall-wxk.github.io/blogDemo/2017/02/05/getStyle.htmlSupplement
Thanks to a contributor for suggesting a canvas‑based approach: capture a screenshot and read pixel colors directly, which solves all edge cases.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
