最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get all style attribute colors - Stack Overflow

programmeradmin1浏览0评论

I'm looking for a way to fetch all css colors from a website. So far, internal as well as external stylesheets could be handled by using document.styleSheets. The problem is that styles that are directly assigned to a tag via a css style attribute won't be in this list.

Is there a better way than iterating through all elements of the DOM and parse the style attribute for each tag? Do you have any other ideas?

I'm looking for a way to fetch all css colors from a website. So far, internal as well as external stylesheets could be handled by using document.styleSheets. The problem is that styles that are directly assigned to a tag via a css style attribute won't be in this list.

Is there a better way than iterating through all elements of the DOM and parse the style attribute for each tag? Do you have any other ideas?

Share Improve this question asked May 24, 2014 at 7:14 G-WakG-Wak 634 silver badges12 bronze badges 2
  • Is there a better way? Not that I know of. – Timo Huovinen Commented May 24, 2014 at 7:16
  • 1 you still have to loop through all the elements, however instead of parsing you can just check the style style.color, if it's empty, there is not any inline color style, otherwise its value is exactly the color you want. – King King Commented May 24, 2014 at 7:22
Add a ment  | 

4 Answers 4

Reset to default 6

This function will return an array of rgb/rgba colors declared via inline styles or CSS classes

function getAllColors() {
    // regex via http://stackoverflow./a/7543829/149636
    var rgbRegex = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/;

    var allColors = [];

    var elems = document.getElementsByTagName('*');
    var total = elems.length;

    var x,y,elemStyles,styleName,styleValue,rgbVal;

    for(x = 0; x < total; x++) {
        elemStyles = window.getComputedStyle(elems[x]);

        for(y = 0; y < elemStyles.length; y++) {
            styleName = elemStyles[y];
            styleValue = elemStyles[styleName];

            if(!styleValue) {
                continue;
            }

            // convert to string to avoid match exceptions
            styleValue += "";

            rgbVal = styleValue.match(rgbRegex);
            if(!rgbVal) { // property does not contain a color
                continue;
            }

            if(allColors.indexOf(rgbVal.input) == -1) { // avoid duplicate entries
                allColors.push(rgbVal.input);
            }

        }

    }

    return allColors;
}

Example: http://jsfiddle/8MqJH/6/

Try this:

  var colorArray = [];
  $("*").each(function(){
    var color = $(this).css("color");
    if(colorArray.indexOf(color) == -1) {
      colorArray.push(color);
    }
  });
  alert(colorArray);

You could try using jQuery to select all elements with style attributes containing "color".

$("[style~=color]")

So if you wanted to put them in an array;

var colors = $("[style~=color]").toArray();

First of all is the question what color attribute do you want to fetch, because there are different ones (color, background-color, border-color, etc...).

Second, to iterate through all elements use:

Array.from(document.body.querySelectorAll("*")).forEach(element =>
{
    // console.log(element);
});

Each element has a style attribute and optional a style sheet rule declaration in document.styleSheets. The style attribute in the element always override the global style sheet rule. To get the style sheet rule declaration of one selected element you need hacks { sad smiley ;-( }, but you can get the current valid used style by using getComputedStyle(element).

Every style daclaration which has a color attribute will be saved in a rgb(0, 0, 0) or rgba(0, 0, 0, 0.5) format in all browsers. Here is not that easy to convert an rgb value to a css color name.

In this example I grab all colors of the current page for "background-color" "color":

document.addEventListener("DOMContentLoaded", event =>
{
    let names = ["background-color", "color"];
    let colors = [];

    var rgbColor =
    {
        'rgb(240, 248, 255)': 'aliceblue',
        'rgb(250, 235, 215)': 'antiquewhite',
        'rgb(0, 255, 255)': 'aqua',
        'rgb(127, 255, 212)': 'aquamarine',
        'rgb(240, 255, 255)': 'azure',
        'rgb(245, 245, 220)': 'beige',
        'rgb(255, 228, 196)': 'bisque',
        'rgb(0, 0, 0)': 'black',
        'rgb(255, 235, 205)': 'blanchedalmond',
        'rgb(0, 0, 255)': 'blue',
        'rgb(138, 43, 226)': 'blueviolet',
        'rgb(165, 42, 42)': 'brown',
        'rgb(222, 184, 135)': 'burlywood',
        'rgb(95, 158, 160)': 'cadetblue',
        'rgb(127, 255, 0)': 'chartreuse',
        'rgb(210, 105, 30)': 'chocolate',
        'rgb(255, 127, 80)': 'coral',
        'rgb(100, 149, 237)': 'cornflowerblue',
        'rgb(255, 248, 220)': 'cornsilk',
        'rgb(220, 20, 60)': 'crimson',
        'rgb(0, 0, 139)': 'darkblue',
        'rgb(0, 139, 139)': 'darkcyan',
        'rgb(184, 134, 11)': 'darkgoldenrod',
        'rgb(169, 169, 169)': 'darkgray',
        'rgb(0, 100, 0)': 'darkgreen',
        'rgb(189, 183, 107)': 'darkkhaki',
        'rgb(139, 0, 139)': 'darkmagenta',
        'rgb(85, 107, 47)': 'darkolivegreen',
        'rgb(255, 140, 0)': 'darkorange',
        'rgb(153, 50, 204)': 'darkorchid',
        'rgb(139, 0, 0)': 'darkred',
        'rgb(233, 150, 122)': 'darksalmon',
        'rgb(143, 188, 143)': 'darkseagreen',
        'rgb(72, 61, 139)': 'darkslateblue',
        'rgb(47, 79, 79)': 'darkslategray',
        'rgb(0, 206, 209)': 'darkturquoise',
        'rgb(148, 0, 211)': 'darkviolet',
        'rgb(255, 20, 147)': 'deeppink',
        'rgb(0, 191, 255)': 'deepskyblue',
        'rgb(105, 105, 105)': 'dimgray',
        'rgb(30, 144, 255)': 'dodgerblue',
        'rgb(178, 34, 34)': 'firebrick',
        'rgb(255, 250, 240)': 'floralwhite',
        'rgb(34, 139, 34)': 'forestgreen',
        'rgb(255, 0, 255)': 'fuchsia',
        'rgb(220, 220, 220)': 'gainsboro',
        'rgb(248, 248, 255)': 'ghostwhite',
        'rgb(255, 215, 0)': 'gold',
        'rgb(218, 165, 32)': 'goldenrod',
        'rgb(128, 128, 128)': 'gray',
        'rgb(0, 128, 0)': 'green',
        'rgb(173, 255, 47)': 'greenyellow',
        'rgb(240, 255, 240)': 'honeydew',
        'rgb(255, 105, 180)': 'hotpink',
        'rgb(205, 92, 92)': 'indianred',
        'rgb(75, 0, 130)': 'indigo',
        'rgb(255, 255, 240)': 'ivory',
        'rgb(240, 230, 140)': 'khaki',
        'rgb(230, 230, 250)': 'lavender',
        'rgb(255, 240, 245)': 'lavenderblush',
        'rgb(124, 252, 0)': 'lawngreen',
        'rgb(255, 250, 205)': 'lemonchiffon',
        'rgb(173, 216, 230)': 'lightblue',
        'rgb(240, 128, 128)': 'lightcoral',
        'rgb(224, 255, 255)': 'lightcyan',
        'rgb(250, 250, 210)': 'lightgoldenrodyellow',
        'rgb(211, 211, 211)': 'lightgray',
        'rgb(144, 238, 144)': 'lightgreen',
        'rgb(255, 182, 193)': 'lightpink',
        'rgb(255, 160, 122)': 'lightsalmon',
        'rgb(32, 178, 170)': 'lightseagreen',
        'rgb(135, 206, 250)': 'lightskyblue',
        'rgb(119, 136, 153)': 'lightslategray',
        'rgb(176, 196, 222)': 'lightsteelblue',
        'rgb(255, 255, 224)': 'lightyellow',
        'rgb(0, 255, 0)': 'lime',
        'rgb(50, 205, 50)': 'limegreen',
        'rgb(250, 240, 230)': 'linen',
        'rgb(128, 0, 0)': 'maroon',
        'rgb(102, 205, 170)': 'mediumaquamarine',
        'rgb(0, 0, 205)': 'mediumblue',
        'rgb(186, 85, 211)': 'mediumorchid',
        'rgb(147, 112, 219)': 'mediumpurple',
        'rgb(60, 179, 113)': 'mediumseagreen',
        'rgb(123, 104, 238)': 'mediumslateblue',
        'rgb(0, 250, 154)': 'mediumspringgreen',
        'rgb(72, 209, 204)': 'mediumturquoise',
        'rgb(199, 21, 133)': 'mediumvioletred',
        'rgb(25, 25, 112)': 'midnightblue',
        'rgb(245, 255, 250)': 'mintcream',
        'rgb(255, 228, 225)': 'mistyrose',
        'rgb(255, 228, 181)': 'moccasin',
        'rgb(255, 222, 173)': 'navajowhite',
        'rgb(0, 0, 128)': 'navy',
        'rgb(253, 245, 230)': 'oldlace',
        'rgb(128, 128, 0)': 'olive',
        'rgb(107, 142, 35)': 'olivedrab',
        'rgb(255, 165, 0)': 'orange',
        'rgb(255, 69, 0)': 'orangered',
        'rgb(218, 112, 214)': 'orchid',
        'rgb(238, 232, 170)': 'palegoldenrod',
        'rgb(152, 251, 152)': 'palegreen',
        'rgb(175, 238, 238)': 'paleturquoise',
        'rgb(219, 112, 147)': 'palevioletred',
        'rgb(255, 239, 213)': 'papayawhip',
        'rgb(255, 218, 185)': 'peachpuff',
        'rgb(205, 133, 63)': 'peru',
        'rgb(255, 192, 203)': 'pink',
        'rgb(221, 160, 221)': 'plum',
        'rgb(176, 224, 230)': 'powderblue',
        'rgb(128, 0, 128)': 'purple',
        'rgb(255, 0, 0)': 'red',
        'rgb(188, 143, 143)': 'rosybrown',
        'rgb(65, 105, 225)': 'royalblue',
        'rgb(139, 69, 19)': 'saddlebrown',
        'rgb(250, 128, 114)': 'salmon',
        'rgb(244, 164, 96)': 'sandybrown',
        'rgb(46, 139, 87)': 'seagreen',
        'rgb(255, 245, 238)': 'seashell',
        'rgb(160, 82, 45)': 'sienna',
        'rgb(192, 192, 192)': 'silver',
        'rgb(135, 206, 235)': 'skyblue',
        'rgb(106, 90, 205)': 'slateblue',
        'rgb(112, 128, 144)': 'slategray',
        'rgb(255, 250, 250)': 'snow',
        'rgb(0, 255, 127)': 'springgreen',
        'rgb(70, 130, 180)': 'steelblue',
        'rgb(210, 180, 140)': 'tan',
        'rgb(0, 128, 128)': 'teal',
        'rgb(216, 191, 216)': 'thistle',
        'rgb(255, 99, 71)': 'tomato',
        'rgb(64, 224, 208)': 'turquoise',
        'rgb(238, 130, 238)': 'violet',
        'rgb(245, 222, 179)': 'wheat',
        'rgb(255, 255, 255)': 'white',
        'rgb(245, 245, 245)': 'whitesmoke',
        'rgb(255, 255, 0)': 'yellow',
        'rgb(154, 205, 50)': 'yellowgreen'
    }

    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);
});
发布评论

评论列表(0)

  1. 暂无评论