DEV Community

Cover image for How to find all the colors used in a Webpage
Lakshmi Sankar
Lakshmi Sankar

Posted on

How to find all the colors used in a Webpage

This is write up of how i created this chrome extension called ColorHunter. The project is also open source, you can find it here: Github.

What we are going to see is the part where we scan all the elements in the webpage and find all the colors.

Step 1: How to get all elements in a webpage?

Simple, the following code will get all the elements in the page and runs a foreach loop on them.

const allElments = document.querySelectorAll<HTMLElement>("*");
allElments.forEach((element) => {
    console.log(element)
});
Enter fullscreen mode Exit fullscreen mode

Step 2: How to get all the colors in a HTML element?

We are using the window.getComputedStyle()method.

const style = window.getComputedStyle(element);
style.color // text color
style.backgroundColor // background color
Enter fullscreen mode Exit fullscreen mode

Step 3: Putting it all these together.

const colors: string[] = [];
const allElments = document.querySelectorAll<HTMLElement>("*");
allElments.forEach((element) => {
    const style = window.getComputedStyle(element);
    colors.push(style.color);
    colors.push(style.backgroundColor);    
});
Enter fullscreen mode Exit fullscreen mode

That’s all.

Project: [Github] [Chrome Extension]

Mine: [Portfolio] | [Github]

Top comments (0)