Skip to content

backgroundColor

Given a DOM element, returns its background color by walking up the ancestor chain until a non-transparent background is found. Falls back to “rgb(255, 255, 255)” (white) if every ancestor is transparent.

Walks up from the element through its ancestors and returns the first computed background that is not transparent, as an rgb() string. Charts use it to pick legible text and stroke colors against whatever the chart is actually sitting on.

import {backgroundColor} from "@d3plus/dom";

backgroundColor(document.querySelector(".inner"));

When nothing on the way up has a background, the walk ends at the page itself: here the documentation page’s white, and if even that is transparent the function falls back to rgb(255, 255, 255).

import {backgroundColor} from "@d3plus/dom";
// Every ancestor transparent: the walk reaches the page, which here is white.
backgroundColor(element); // "rgb(255, 255, 255)"

Parameters

import {backgroundColor} from "@d3plus/dom";
elemrequiredBaseType | undefined

The DOM element to check.