To begin with, the important question is which specific color attribute you are interested in retrieving - whether it's color, background-color, border-color, etc...
Secondly, if you want to iterate through all elements on a page, you can use this code:
Array.from(document.body.querySelectorAll("*")).forEach(element =>
{
// console.log(element);
});
Each element carries a style attribute and may have an associated style sheet rule declaration within document.styleSheets. The local style attribute of an element always takes precedence over the global style sheet rule. To access the style sheet rule declaration for a particular element, some workarounds may be needed { sad smiley ;-( }, but you can retrieve the currently applied valid style using getComputedStyle(element).
All color-related style declarations will be represented in browsers as either rgb(0, 0, 0) or rgba(0, 0, 0, 0.5) formats. Converting an rgb value to a CSS color name isn't as straightforward.
In the following example, I am extracting all colors used for "background-color" and "color" on the current page:
document.addEventListener("DOMContentLoaded", event =>
{
let names = ["background-color", "color"];
let colors = [];
var rgbColor =
{
// Define RGB values corresponding to CSS color names
...
}
names.forEach(name =>
{
Array.from(document.body.querySelectorAll("*")).forEach(element =>
{
let style = getComputedStyle(element);
let value = style[name]; if(!value) { return; }
if(value in rgbColor) { value = rgbColor[value]; }
if(!colors.includes(value))
{
colors.push(value);
}
});
});
console.log(colors);
});