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)
});
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
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);
});
That’s all.
Project: [Github] [Chrome Extension]
Top comments (0)