Search code examples
javascripthtmlcsscode-injection

How come this color assignment is not affecting all elements on the page?


I'm working off this answer, except with pure Javascript, and not jquery. I've attempted to change all elements that have a color assignment to a pink color. I'm walking through the elements backwards in my loop. Injecting this code on https://en.wikipedia.org/wiki/Main_Page, for example, only changes a few background colors; leaving many untouched, even though inspecting the element has a CSS color property. How come this color assignment is not affecting all elements on the page that have a color property?

// CSS properties that can change color
let CSSPropsColor =
[
"background",
"background-color",
"text-shadow",
"text-decoration-color",
"text-emphasis-color",
"caret-color",
"border-color",
"border-left-color",
"border-right-color",
"border-top-color",
"border-bottom-color",
"border-block-start-color",
"border-block-end-color",
"border-inline-start-color",
"border-inline-end-color",
"column-rule-color",
"outline-color",
"color",
]

function pinkAll()
{
    // get all elements
    var allEl = document.getElementsByTagName("*");
    
    // walk backwards through loop
    for (var i=allEl.length-1; i > -1; i--) {
            var color = null;
            
            for (var prop in CSSPropsColor) {
                prop = CSSPropsColor[prop];
                
                //if we can't find this property or it's null, continue
                if (!allEl[i].style[prop]) continue;
                
                var bgColor = window.getComputedStyle(allEl[i],null).getPropertyValue(prop).toString();
                
                let firstChar = bgColor.charAt(0);
                
                if(firstChar !== "r" && firstChar !== "#") continue;
                
                allEl[i].style[prop] = "#EC00FF" // change element color to PINK
                
            }
    }
}

window.addEventListener('load', function () {
    // sometimes 'load' is not enough, and I have to wait a bit
    let timeout = setTimeout(pinkAll, 500);
})

Solution

  • Your if statement: if (!allEl[i].style[prop]) continue; is continuing anytime it encounters an element wherein the style is not set inline. Using if (!window.getComputedStyle(allEl[i],null).getPropertyValue(prop)) continue; sets the whole page pink...