Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a css rule exists

I need to check if a CSS rule exists because I want to issue some warnings if a CSS file is not included.

What is the best way of doing this?

I could filter through window.document.styleSheets.cssRules, but I'm not sure how cross-browser this is (plus I notice on Stack Overflow that object is null for styleSheet[0]).

I would also like to keep dependencies to a minimum.

Is there a straightforward way to do this? Do I just have to create matching elements and test the effects?

Edit: If not, what are the cross-browser concerns of checking window.document.styleSheets?

like image 966
George Mauer Avatar asked Nov 01 '11 19:11

George Mauer


Video Answer


2 Answers

Here is what I got that works. It's similar to the answers by @Smamatti and @jfriend00 but more fleshed out. I really wish there was a way to test for rules directly but oh well.

CSS:

.my-css-loaded-marker { 
  z-index: -98256; /*just a random number*/
}

JS:

$(function () { //Must run on jq ready or $('body') might not exist

    var dummyElement = $('<p>')
                  .hide().css({height: 0, width: 0})
                  .addClass("my-css-loaded-marker")
                  .appendTo("body");  //Works without this on firefox for some reason

    if (dummyElement.css("z-index") != -98256 && console && console.error) {
        console.error("Could not find my-app.css styles. Application requires my-app.css to be loaded in order to function properly");
    }
    dummyElement.remove();
});
like image 72
George Mauer Avatar answered Oct 18 '22 17:10

George Mauer


I test for proper CSS installation using javascript.

I have a CSS rule in my stylesheet that sets a particular id to position: absolute.

#testObject {position: absolute;}

I then programmatically create a temporary div with visibility: hidden with that ID and get the computed style position. If it's not absolute, then the desired CSS is not installed.


If you can't put your own rule in the style sheet, then you can identify one or more rules that you think are representative of the stylesheet and not likely to change and design a temporary object that should get those rules and test for their existence that way.

Or, lastly, you could try to enumerate all the external style sheets and look for a particular filename that is included.

The point here is that if you want to see if an external style sheet is included, you have to pick something about that style sheet that you can look for (filename or some rule in it or some effect it causes).

like image 39
jfriend00 Avatar answered Oct 18 '22 15:10

jfriend00