[javascript] How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

I tried this, but it doesn't work:

<!--[if IE 10]>    <html class="no-js ie10" lang="en"> <![endif]-->
<!--[if !IE]><!--> <html lang="en" class="no-js"> <!--<![endif]-->

Internet Explorer 10 ignores the conditional comments and uses the <html lang="en" class="no-js"> instead of <html class="no-js ie10" lang="en">.

The answer is


A good place to start is the IE Standards Support Documentation.

Here is how to target IE10 in JavaScript:

if ("onpropertychange" in document && !!window.matchMedia) {
...
}

Here is how to target IE10 in CSS:

@media all and (-ms-high-contrast: none) {
...
}

In case IE11 needs to be filtered or reset via CSS, see another question: How to write a CSS hack for IE 11?


Internet Explorer 10 does not attempt to read conditional comments anymore. This means it will treat conditional comments just like any other browser would: as regular HTML comments, meant to be ignored entirely. Looking at the markup given in the question as an example, all browsers including IE10 will ignore the comment portions, highlighted gray, entirely. The HTML5 standard makes no mention of conditional comment syntax, and this is exactly why they have chosen to stop supporting it in IE10.

Note, however, that conditional compilation in JScript is still supported, as shown in the comments as well as the more recent answers. It's not going away in the final release either, unlike jQuery.browser. And of course, it goes without saying that user-agent sniffing remains as fragile as ever and should never be used under any circumstances.

If you really must target IE10, either use conditional compilation which may still see support in the near future, or — if you can help it — use a feature detection library such as Modernizr instead of (or in conjunction with) browser detection. Unless your use case requires noscript or accommodating IE10 on the server side, user-agent sniffing is going to be more of a headache than a viable option.

Sounds pretty cumbersome, but remember that as a modern browser that's highly conformant to today's Web standards1, assuming you've written interoperable code that is highly standards-compliant, you shouldn't have to set aside special code for IE10 unless absolutely necessary, i.e. it's supposed to resemble other browsers in terms of behavior and rendering.2 And it sounds far-fetched, given IE's history, but how many times have you expected Firefox or Chrome to behave the same way only to be met with dismay?

If you do have a legitimate reason to be targeting certain browsers, by all means sniff them out with the other tools given to you. I'm just saying that you're going to be much more hard-pressed to find such a reason today than what it used to be, and it's really just not something you can rely on.


1 Not only IE10, but IE9, and even IE8 which handles most of the mature CSS2.1 standard far better than Chrome, simply because IE8 was so focused on standards compliance (at which time CSS2.1 was already pretty stable with only minor differences from today's recommendation) while Chrome seems to be little more than a half-polished tech demo of cutting-edge pseudo-standards.

2 And I may be biased when I say this, but it sure as hell does. If your code works in other browsers but not IE, the odds that it's an issue with your own code rather than IE10 are far better compared to, say, 3 years ago, with previous versions of IE. Again, I may be biased, but let's be honest: aren't you too? Just look at your comments.


I use this script - it's antiquated, but effective in targeting a separate Internet Explorer 10 style sheet or JavaScript file that is included only if the browser is Internet Explorer 10, the same way you would with conditional comments. No jQuery or other plugin is required.

<script>
    /*@cc_on
      @if (@_jscript_version == 10)
          document.write(' <link type= "text/css" rel="stylesheet" href="your-ie10-styles.css" />');
      @end
    @*/
</script >

If you must do this, you can check the user agent string in JavaScript:

var isIE10 = !!navigator.userAgent.match(/MSIE 10/);

As other people have mentioned, I'd always recommend feature detection instead.


If you don't mind targeting of IE10 and above and non IE browsers, you can use this conditional comment:

<!--[if gt IE 9]><!--> Your code here. <!--<![endif]-->

Derived from http://www.paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither


If you want to target IE 10 with Vanilla JavaScript, you might want to try CSS property detection:

if (document.body.style.msTouchAction != undefined) {
  document.body.className = 'ie10';
}

CSS properties

Instead of msTouchAction you can also use one of these CSS properties, because they are currently only available in IE 10. But this might change in the future.

  • msTouchAction
  • msWrapFlow
  • msWrapMargin
  • msWrapThrough
  • msScrollLimit
  • msScrollLimitXMin
  • msScrollLimitYMin
  • msScrollLimitXMax
  • msScrollLimitYMax
  • msFlexbox
  • msFlex
  • msFlexOrder

Test page

I've put together a test page with all properties on CodePen.


use babel or typescript for convert this code js

_x000D_
_x000D_
const browser = () => {_x000D_
    // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3576.0 Safari/537.36"_x000D_
    // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.17 Safari/537.36"_x000D_
    // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763"_x000D_
    // "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0"_x000D_
    // "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; rv:11.0) like Gecko"_x000D_
    // "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)"_x000D_
    // "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)"_x000D_
    // "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)"_x000D_
    // "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)"_x000D_
    const _userAgent = navigator.userAgent;_x000D_
    const br = {_x000D_
        "Chrome": "Chrome",_x000D_
        "Edge": "Edge",_x000D_
        "Firefox": "Firefox",_x000D_
        ".NET CLR": "Internet Explorer 11",_x000D_
    };_x000D_
    const nobr = {_x000D_
        "MSIE 10.0": "Internet Explorer 10",_x000D_
        "MSIE 9.0": "Internet Explorer 9",_x000D_
        "MSIE 8.0": "Internet Explorer 8",_x000D_
        "MSIE 7.0": "Internet Explorer 7"_x000D_
    };_x000D_
    let thisBrow = "Unknown";_x000D_
    for (const keys in br) {_x000D_
        if (br.hasOwnProperty(keys)) {_x000D_
            if (_userAgent.includes(keys)) {_x000D_
_x000D_
                thisBrow = br[keys];_x000D_
_x000D_
                for (const key in nobr) {_x000D_
                    if (_userAgent.includes(key)) {_x000D_
                        thisBrow = nobr[key];_x000D_
                    }_x000D_
                }_x000D_
_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
_x000D_
    return thisBrow;_x000D_
};
_x000D_
_x000D_
_x000D_


This answer got me 90% of the way there. I found the rest of my answer on the Microsoft site here.

The code below is what I'm using to target all ie by adding a .ie class to <html>

Use jQuery (which deprecated .browser in favor of user agents in 1.9+, see http://api.jquery.com/jQuery.browser/) to add an .ie class:

// ie identifier
$(document).ready(function () {
  if (navigator.appName == 'Microsoft Internet Explorer') {
    $("html").addClass("ie");
  }
});

Check out http://suhasrathod.wordpress.com/2013/04/29/ie10-css-hacks/

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
       /* IE10-specific styles go here */
}

For me the following code works fine, all conditional comments are working in all IE versions:

<!--[if lt IE 7 ]> <html class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html class="ie8"> <![endif]-->
<!--[if IE 9 ]>    <html class="ie9"> <![endif]-->
<!--[if (gt IE 11)|!(IE)]><!--> <html> <!--<![endif]-->

<script>
    if (document.documentMode===10){
        document.documentElement.className+=' ie10';
    }
    else if (document.documentMode===11){
        document.documentElement.className+=' ie11';
    }
</script>

I'm on windows 8.1, not sure if it's related to ie11 update...


You could use feature detection to see if browser is IE10 or greater like so:

var isIE = false;
if (window.navigator.msPointerEnabled) {
    isIE = true;
}

Only true if > IE9


I found a solution on this site where someone had a valuable comment:

The solution is:

if (Function('/*@cc_on return document.documentMode===10@*/')()){
    document.documentElement.className+=' ie10';
}

It

  • doesn’t need conditional comments;
  • works even if comment stripping compression/processing;
  • no ie10 class added in Internet Explorer 11;
  • more likely to work as intended with Internet Explorer 11 running in Internet Explorer 10 compatibility mode;
  • doesn’t need standalone script tag (can just be added to other JavaScript code in the head).
  • doesn't need jQuery to test

clipBoardData is a function that is only available in IE, so if you are seeking to target all IE versions you can use

<script type="text/javascript">
if (window.clipboardData)
            alert("You are using IE!");
</script>

I wouldn't use JavaScript navigator.userAgent or $.browser (which uses navigator.userAgent) since it can be spoofed.

To target Internet Explorer 9, 10 and 11 (Note: also the latest Chrome):

@media screen and (min-width:0\0) { 
    /* Enter CSS here */
}

To target Internet Explorer 10:

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    /* IE10+ CSS here */
}

To target Edge Browser:

@supports (-ms-accelerator:true) {
  .selector { property:value; } 
}

Sources:


CSS for IE10+ and IE9

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    /* IE10+ styles */
}

@media screen\0 {
    /* IE8,9,10 styles*/
}

Here is how I do custom CSS for Internet Explorer:

In my JavaScript file:

function isIE () {
      var myNav = navigator.userAgent.toLowerCase();
      return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

jQuery(document).ready(function(){
    if(var_isIE){
            if(var_isIE == 10){
                jQuery("html").addClass("ie10");
            }
            if(var_isIE == 8){
                jQuery("html").addClass("ie8");
                // you can also call here some function to disable things that 
                //are not supported in IE, or override browser default styles.
            }
        }
    });

And then in my CSS file, y define each different style:

.ie10 .some-class span{
    .......
}
.ie8 .some-class span{
    .......
}

I just wanted to add my version of IE detection. It's based on a snippet found at http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/ and exteded to also support ie10 and ie11. It detects IE 5 to 11.

All you need to do is add it somewhere and then you can always check with a simple condition. The global var isIE will be undefined if it's not an IE, or otherwise it will be the version number. So you can easily add things like if (isIE && isIE < 10) or alike.

var isIe = (function(){
    if (!(window.ActiveXObject) && "ActiveXObject" in window) { return 11; /* IE11 */ }
    if (Function('/*@cc_on return /^10/.test(@_jscript_version) @*/')()) { return 10; /* IE10  */ }
    var undef,
        v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
            all[0]
        );
    return v > 4 ? v : undef;
}());

Both solutions posted here (with slight modifications) work:

<!--[if !IE]><!--><script>if(/*@cc_on!@*/false){document.documentElement.className='ie10';}</script><!--<![endif]-->

or

<script>if(Function('/*@cc_on return 10===document.documentMode@*/')()){document.documentElement.className='ie10';}</script>

You include either of the above lines inside of head tag of your html page before your css link. And then in css file you specify your styles having "ie10" class as a parent:

.ie10 .myclass1 { }

And voilà! - other browsers stay intact. And you don't need jQuery. You can see the example how I implemented it here: http://kardash.net.


With JavaScript:

if (/Trident/g.test(navigator.userAgent)) { // detect trident engine so IE
        document.getElementsByTagName('html')[0].className= 'no-js ie'; }

Work for all IE.

IE08 => 'Trident/4.0'

IE09 => 'Trident/5.0'

IE10 => 'Trident/6.0'

IE11 => 'Trident/7.0'

So change /Trident/g by /Trident/x.0/g where x = 4, 5, 6 or 7 (or maybe 8 for the future).


modern solution for css

html[data-useragent*='MSIE 10.0'] .any {
  your-style: here;
}

I've written a small, vanilla JavaScript plugin called Layout Engine, which allows you to feature detect IE 10 (and every other browser), in a simple way that cannot be faked, unlike user agent sniffing.

It adds the rendering engine name as a class on the html tag and returns a JavaScript object containing the vendor and version (where appropriate)

Check out my blog post: http://mattstow.com/layout-engine.html and get the code on GitHub: https://github.com/stowball/Layout-Engine


Conditionizr (see docs) will add browser CSS classes to your html element, including ie10.


You can use PHP to add a stylesheet for IE 10

Like:

if (stripos($_SERVER['HTTP_USER_AGENT'], 'MSIE 10')) {
    <link rel="stylesheet" type="text/css" href="../ie10.css" />
}

If you really have to, you can make conditional comments work by adding the following line to <head>:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">

Source


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to internet-explorer-10

Force IE10 to run in IE10 Compatibility View? internet explorer 10 - how to apply grayscale filter? How to force IE10 to render page in IE9 document mode Remove IE10's "clear field" X button on certain inputs? Registry key for global proxy settings for Internet Explorer 10 on Windows 8 How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

Examples related to conditional-comments

<!--[if !IE]> not working How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code? is there any IE8 only css hack?