7

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 I've made some CSS-popups with checkboxes and needs to do fallbacks for old browsers.

ANSWER: I'm found already implemented method of testing css selectors in a Modernizr "Additional Tests".

Sam Hanley
  • 4,707
  • 7
  • 35
  • 63
Raiden
  • 135
  • 1
  • 6
  • 1
    [Modernizr](http://www.modernizr.com/) detects many things like that. –  Dec 16 '11 at 09:11
  • I know about Modernizr, but it's don't have tests for css3 pseudo-classes support, only pseudo-elements like `::before`, etc. – Raiden Dec 16 '11 at 10:00

4 Answers4

3

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);
    }
    return function (pseudo_class){
        try{
            if(!(/^:/).test(pseudo_class)){
                pseudo_class = ':'+pseudo_class;
            }
            ss.insertRule('html'+pseudo_class+'{}',0);
            ss.deleteRule(0);
            return true;
        }catch(e){
            return false;
        }
    };
}();


//test
support_pseudo(':hover'); //true
support_pseudo(':before'); //true
support_pseudo(':hello'); //false
support_pseudo(':world'); //false
John
  • 1
  • 13
  • 98
  • 177
cuixiping
  • 24,167
  • 8
  • 82
  • 93
3

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.

function supportsSelector (selector) {
  const style = document.createElement('style')
  document.head.appendChild(style)
  try {
    style.sheet.insertRule(selector + '{}', 0)
  } catch (e) {
    return false
  } finally {
    document.head.removeChild(style)
  }
  return true
}

supportsSelector(':hover') // true
supportsSelector(':fake') // false
nlawson
  • 11,510
  • 4
  • 40
  • 50
3

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

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

andychups
  • 82
  • 3
  • 5
    Found already implemented [method](https://gist.github.com/441842) of testing css selectors in a Modernizr ["Additional Tests"](https://github.com/Modernizr/Modernizr/wiki). Oh, god, why it's not in the core? – Raiden Dec 17 '11 at 09:16
  • Working solution, but a bit ugly – franzlorenzon Mar 28 '13 at 10:57
1

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

Interrobang
  • 16,984
  • 3
  • 55
  • 63
  • 3
    It will be better do not use Selectivizr, because perfomance is dicreasing due to parse CSS before rendering page. – andychups Dec 16 '11 at 10:25