2

I am building menus that rely on the css :after and :before pseudo selectors. How can I detect if the browser supports them?

I found this article that explains how to detect css properties that can be accessed in JavaScript, but it doesn't seem to apply to my case.

[Edit] In answer to the comments and first replies:

  • The pseudo-selectors add elements, for example arrows for breadcrumb navigation.
  • I prefer feature detection to browser detection, because some browsers will work in quirks mode (typically IE 8 / IE 9)
Christophe
  • 27,383
  • 28
  • 97
  • 140
  • Just out of curiosity, why do you want to do this? – putvande Oct 17 '13 at 15:50
  • 2
    And what does “rely” mean in this case? What would be missing or even broken in your menu if they were not supported? – CBroe Oct 17 '13 at 15:50
  • possible duplicate of [How to detect if browser support specified css pseudo-class?](http://stackoverflow.com/questions/8531940/how-to-detect-if-browser-support-specified-css-pseudo-class) – isherwood Oct 17 '13 at 15:55
  • @isherwood `::before` and `::after` are not pseudo classes. – iConnor Oct 17 '13 at 15:57

3 Answers3

2

Well, they're supported in every browser other than IE 7 and under, so this should do.

<!--[if lt IE 8]>
  <script> window.contentSupported = false; </script>
<![endif]-->

and in your javascript you can do.

if(window.contentSupported !== false) {
   // :before is supported
} else {
   // :before isn't supported
}
iConnor
  • 19,997
  • 14
  • 62
  • 97
1

As you can see here http://caniuse.com/#search=after, :after and :before selectors are supported by every browsers except earlier version of IE8. You could check by a script or conditional comment if the browser is IE and if the version is earlier than version 8.

http://modernizr.com/download/ This is a really good tool to detect which features a browser is able to understand. It's a library, that adds a css class to your html body tag. In your case you have just to check the option for "Css generated content :before and :after".

Mela
  • 23
  • 3
1
document.querySelector(':after, :before');
StuR
  • 12,042
  • 9
  • 45
  • 66
  • I like that! Let me do some testing. Why body btw? Based on the other answers, I am actually thinking that document.querySelector could be enough. – Christophe Oct 17 '13 at 16:13
  • It doesn't have to be body, just document will do. – StuR Oct 17 '13 at 16:18
  • 1
    Minor comment: you actually need to do it in 2 steps (document.querySelector)&&(document.querySelector(':after, :before')) – Christophe Oct 17 '13 at 16:29