Skip to content Skip to sidebar Skip to footer

How To Detect If Browser Support Specified Css Pseudo-class?

What's concept of detecting support of any css pseudo-class in browser through JavaScript? Exactly, I want to check if user's browser supports :checked pseudo-class or not, because

Solution 1:

You can simply check if your style with pseudo-class was applied.

Something like this: http://jsfiddle.net/qPmT2/1/

Solution 2:

stylesheet.insertRule(rule, index) method will throw error if the rule is invalid. so we can use it.

var support_pseudo = function (){
    var ss = document.styleSheets[0];
    if(!ss){
        var el = document.createElement('style');
        document.head.appendChild(el);
        ss = document.styleSheets[0];
        document.head.removeChild(el);
    }
    returnfunction (pseudo_class){
        try{
            if(!(/^:/).test(pseudo_class)){
                pseudo_class = ':'+pseudo_class;
            }
            ss.insertRule('html'+pseudo_class+'{}',0);
            ss.deleteRule(0);
            returntrue;
        }catch(e){
            returnfalse;
        }
    };
}();


//testsupport_pseudo(':hover'); //truesupport_pseudo(':before'); //truesupport_pseudo(':hello'); //falsesupport_pseudo(':world'); //false

Solution 3:

If you're OK with using Javascript, you might skip the detection and go right for the shim: Selectivizr

Solution 4:

For anyone still looking for a quick solution to this problem, I cribbed together something based on a few of the other answers in this thread. My goal was to make it succinct.

functionsupportsSelector (selector) {
  const style = document.createElement('style')
  document.head.appendChild(style)
  try {
    style.sheet.insertRule(selector + '{}', 0)
  } catch (e) {
    returnfalse
  } finally {
    document.head.removeChild(style)
  }
  returntrue
}

supportsSelector(':hover') // truesupportsSelector(':fake') // false

Post a Comment for "How To Detect If Browser Support Specified Css Pseudo-class?"