0

I am writing a Greasemonkey script and at some point in the script, I want to change the background colour of every element on the page that currently has one. I know I can get elements from their ID, and change their CSS, like so:

document.getElementById("char").style.backgroundColor = "#FFFFFF";

But is it possible to do this the other way around, which would be much faster than looping through every element on the page to check if it has a background colour and change it?

// use a new background colour instead
document.getElementByCSS("background-color").style.backgroundColor = "#FFFFFF";

I'd like to avoid JQuery.

tomysshadow
  • 870
  • 1
  • 8
  • 23

2 Answers2

0

As per what Musa said above "With inline css you could do document.querySelectorAll('[style*="background-color"]') but I cant see any way for computed styles." my case involves inline CSS and so it's all good.

tomysshadow
  • 870
  • 1
  • 8
  • 23
0

I wouldn't recommend it but you could use this function

function findByCss( prop, val ) {
        var 
        retArr = [],
        allElms = document.getElementsByTagName('*'),
        computed,
        i = 0;
        for ( ; i < allElms.length; i++ ) {
            computed = window.getComputedStyle( allElms[i], null ).getPropertyValue(prop);
            if ( computed.indexOf( val ) >= 0 ) {
                retArr.push( allElms[ i ] );
            }
        }

        return retArr;

    }

It returns an array of elements which computed styles CONTAIN the value of the style property you are looking for, you can change it to be an less tolerant conditional if you would like. On another note all hex color codes get computed as RBG, so you would have to find the RGB value for the hex code before using this function in your case.

undefined
  • 2,154
  • 15
  • 16