0

I'm looking for a way to get a page's css with js without looking at a particular element, and then change the CSS rules rather than the CSS for different elements.

For instance, let say I want to change the background color of all elements that have a blue bg to red, and that after that some new elements might be created. I'd like to find all the css classes with blue bg and change them to red. document.styleSheets doesn't seem to work that well:

For this page I tried this in the console. It doesn't log anything.

var logAttr = function(classes){
    if(classes !== null){
        for(var i = 0; i < classes.length; i++) {
            for(var attr in classes[i].style){
                console.log(attr);
            }
        }
    }
};

for(var sheets_idx = 0; sheets_idx < document.styleSheets.length; sheets_idx++){
    logAttr(document.styleSheets[sheets_idx].rules);
    logAttr(document.styleSheets[sheets_idx].cssRules);
}

document.styleSheets[0].rules and document.styleSheets[0].document.styleSheets are null...

1
  • Why doesn't document.styleSheets seem to work that well? What did you try? Commented Oct 19, 2014 at 4:18

1 Answer 1

1

I'm sure that stylesheets do work well, probably you just didn't manage to get your example working: take a look at this.

var sheet = (function() {
    // Create the <style> tag
    var style = document.createElement("style");

    // Add a media (and/or media query) here if you'd like!
    // style.setAttribute("media", "screen")
    // style.setAttribute("media", "only screen and (max-width : 1024px)")

    // WebKit hack :(
    style.appendChild(document.createTextNode(""));

    // Add the <style> element to the page
    document.head.appendChild(style);

    return style.sheet;
})();

That creates a stylesheet for you with all of the right conditions to work in. Now, to insert a rule in string form, you simply use this thing:

sheet.insertRule('div {position: absolute; top:0px; width:10vh; height:10vw;}')

In case you simply want to add a rule to an existing ruleset:

sheet.addRule('div', 'background-color: red');

If you want to use a custom function to do this, simply call sheet.addRule with certain arguments:

function add(query, property){

    //don't forget that you need to have already created the sheet!
    sheet.addRule(query, property);
}

The query can be anything accessible through css: .class, #id, h1, #id > h1 > .class

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your clear answer on how to change CSS rules! It seems that the reason document.styleSheets is not working is discussed here link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.