Assuming...
- ...that it's the crunky rendering engine of old versions of IE you're interested in detecting, to make a style look right in old IE (otherwise, use feature detection)
- ...that you can't just add conditional comments to the HTML - e.g. for JS plugins that can be applied to any page (otherwise, just do the trick of conditional classes on
<body>
or <html>
)
...then this is probably the best trick (based on this non-jQuery, slightly less flexible variant). It creates then tests for then removes an appropriate conditional comment.
(Conditional comments are ignored in IE10+ 'standards mode' - but that should be fine since IE10+ 'standards mode' doesn't have a crazy rendering engine!)
Drop in this function:
function isIE( version, comparison ){
var $div = $('<div style="display:none;"/>');
// Don't chain these, in IE8 chaining stops some versions of jQuery writing the conditional comment properly
$div.appendTo($('body'));
$div.html('<!--[if '+(comparison||'')+' IE '+(version||'')+']><a> </a><![endif]-->');
var ieTest = $div.find('a').length;
$div.remove();
return ieTest;
}
Then use it like this:
if(isIE()){ /* runs in all versions of IE after 4 before standards-mode 10 */ }
if(isIE(8)){ /* runs in IE8 */ }
if(isIE(9)){ /* runs in IE9 */ }
if(isIE(8,'lte')){ /* runs in IE8 or below */ }
if(isIE(6,'lte')){ /* if you need this, I pity you... */ }
I'd also suggest caching the results of this function so you don't have to repeat it. For example, you could use the string (comparison||'')+' IE '+(version||'')
as a key to store and check for the result of this test in an object somewhere.