user2635299
user2635299

Reputation: 95

Changing the element style inside the iframe dynamically

I have an iframe, inside that background color should change to black and body color to white. And all the elements which has color black by deafult which was loaded from external stylesheet also need to be changed to white color. The first thing I did to change the background color and color of body text is :

    frame = document.getElementsByTagName(“iframe”);
    var D = frame.contentDocument;  
    var cwin = frame.contentWindow;
    D.body.style.backgroundColor ='black';  
    D.body.style.color = 'white';

But the elements which has color black will become invisible due to its style. So I traversed through the dom to get the elements which has color black and change it to white. But the below code doesnt seem to work.

var all = D.getElementsByTagName("*");
                for (var i=0, max=all.length; i < max; i++) {
                    computedStyle = cwin.getComputedStyle(all[i]);
                    var c = computedStyle.getPropertyValue("color"); 
                    if(c =='rgb(0,0,0)'){
                        all[i].style.setProperty("color", "white", null);
                    }
                }

Note:Stylesheet are loaded externally. I can't manually change the external style-sheet, I want to do it at run time. Any better solution or modification for the above code?

Upvotes: 0

Views: 1052

Answers (1)

Spiny Norman
Spiny Norman

Reputation: 8347

If c has the value "rgb(0, 0, 0)", then the condition c == 'rgb(0,0,0)' will be false, because the tested string is 2 characters (spaces) longer than the expected string.

You could try changing your line to if(c =='rgb(0, 0, 0)'){.

However, different browsers may have different representations for the value "black". If you want to be sure that you will always get the same representation of black (#000, rgb(0, 0, 0)), you can try normalizing the string to a fixed format, as explained here.

There also seems to be a more comprehensive color converter (Stoyan's RGBColor.js) that is actively worked on here (the original is here).

Upvotes: 1

Related Questions