1

I know this is an old question. I want to add browser specific classes for different browsers mainly for IE versions.

I used below mentioned code:

<!--[if IE 7 ]>    <html dir="ltr" lang="en-US" class="ie ie7 lte8 lte9"> <![endif]-->
<!--[if IE 8 ]>    <html dir="ltr" lang="en-US" class="ie ie8 lte8 lte9"> <![endif]-->
<!--[if IE 9 ]>    <html dir="ltr" lang="en-US" class="ie ie9 lte9"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html dir="ltr" lang="en-US" class="not-ie"><!--<![endif]-->

Here problem is now conditional comments are gone form ie10+ and I want specific class for all ie versions. Even it would great if I also get class for webkit and moz browsers.

Purpose of this to remove all css hacks from my existing stylesheet.

I want something should work like this and JScript solution is also acceptable.

<!--[if IE 7 ]>    <html dir="ltr" lang="en-US" class="ie ie7 lte8 lte9"> <![endif]-->
<!--[if IE 8 ]>    <html dir="ltr" lang="en-US" class="ie ie8 lte8 lte9"> <![endif]-->
<!--[if IE 9 ]>    <html dir="ltr" lang="en-US" class="ie ie9 lte9"> <![endif]-->
<!--[if IE 10 ]>    <html dir="ltr" lang="en-US" class="ie ie10"> <![endif]--> <!--no more work for 1e10+ -->
<!--[if IE 11 ]>    <html dir="ltr" lang="en-US" class="ie ie11"> <![endif]--> <!--no more work for 1e10+ -->
<!--[if !IE]><!--><html dir="ltr" lang="en-US" class="not-ie"><!--<![endif]-->
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Praveen
  • 1,772
  • 3
  • 24
  • 42

7 Answers7

2

Use following JavaScript code, it will add IE version class in HTML tag:

Source:

(function () {
    var v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i'),
        browser,
        isIE;

    while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0]);
    v = v > 4 ? v : document.documentMode;
    if (v) {
        browser = " ie"
        for(var i = 5; i<12; i++){
            if(v < i) {
                browser += ' lte-ie' + i;
            }else if (v > i) {
                browser += ' gte-ie' + i;
            }else if (v == i) {
                browser += ' ie' + i;
            }
        }

        isIE = {
            "version" : v
        }

    } else {
        browser = ' not-ie';
        isIE = false;
    }
    document.documentElement.className += browser;
    window.ie = isIE;
}());

Minified:

(function(){for(var a=3,b=document.createElement("div"),c=b.getElementsByTagName("i");b.innerHTML="\x3c!--[if gt IE "+ ++a+"]><i></i><![endif]--\x3e",c[0];);if(a=4<a?a:document.documentMode){b=" ie";for(c=5;12>c;c++)a<c?b+=" lte-ie"+c:a>c?b+=" gte-ie"+c:a==c&&(b+=" ie"+c);a={version:a}}else b=" not-ie",a=!1;document.documentElement.className+=b;window.ie=a})();

Comment:

Since the script is supporting IE5 and above, I'm keeping all version detection. It may not be useful for you but someone else can find it helpful. And there is no harm of having extra CSS classes.

Ovais
  • 374
  • 2
  • 7
  • By the way, in most cases, you can know if a feature is supported with a simple if statement. – Bob Aug 29 '14 at 18:23
  • I know, but some time developer requires some conditional CSS targeting specific browser version of IE. With above script you can write like ".ie8 .someDiv{}" – Ovais Aug 29 '14 at 18:26
  • thanks..@Ovais Mohd..it works, could u make it work like for ie7-ie9 it should has class ".lte-ie10" and ie7-ie8 has common class ".lte-ie9" – Praveen Aug 29 '14 at 18:37
  • Hi Praveen, I've made changes in script as request. Can you mark answer as 'Accepted Answer'? – Ovais Aug 29 '14 at 19:38
2

In javascript you can use the navigator.userAgent variable and check if it match the IE user agent (MSIE ** or Trident/**)

Warning : Trident is the new way to check for IE:

var newIEReg = new RegExp("Trident\/([0-9]+)\.0")
var oldIEReg = new RegExp("MSIE ([0-9]+)\.[0-5]+")
var ieVersion = -1;
if(navigator.userAgent.match(newIEReg))
{
   ieVersion = parseInt(newIEReg.$1) + 4;
}
else if(navigator.userAgent.match(oldIEReg))
{
   ieVersion = parseInt(oldIEReg.$1);
}
Q-B
  • 120
  • 1
  • 3
0

Each browser has a user agent, so you can use something like following:

var user_agent = navigator.userAgent;
if(user_agent=="BROWSER_USER_AGENT"){
   // your code
}

The user agents list is available online.

Bob
  • 436
  • 5
  • 13
0

See this JSFiddle for an example.

This supports IE 7 - 11, WebKit (Chrome, Safari etc.) and Gecko (Firefox etc.).

Detect the user agent with JavaScript and apply a class to the body depending on which browser:

<script>
var ua = navigator.userAgent;
if (!ua.contains("MSIE")) { // If it doesn't contain MSIE
    document.body.classList.add("not-ie");
    if (ua.contains("(Windows NT 6.3; Trident/7.0; rv:11.0)")) {            
    // IE11 pretends to not be IE and doesn't contain MSIE in the 
    // default user agent, but it contains the string above
        document.body.classList.remove("not-ie");
        document.body.classList.add("ie", "ie11");
    } else if(ua.contains("Gecko")) {
        document.body.classList.add("gecko");
    } else if(ua.contains("WebKit")) {
        document.body.classList.add("webkit");
    }
} else {
    document.body.classList.add("ie");
    if (ua.contains("11.0")) {
        // Just in case we're using an alternative user agent
        document.body.classList.add("ie11");
    } else if (ua.contains("10.6") || ua.contains("10.0")) {
        document.body.classList.add("ie10");
    } else if (ua.contains("9.0")) {
        document.body.classList.add("ie9");
    } else if (ua.contains("8.0")) {
        document.body.classList.add("ie8");
    } else if (ua.contains("7.0")) {
        document.body.classList.add("ie7");
    };
};
</script>
Taha Paksu
  • 15,371
  • 2
  • 44
  • 78
DevilishDB
  • 595
  • 6
  • 12
0

Main Solution:

I forgot where I got this function so I can't properly give credit to it but it works really well:

function getInternetExplorerVersion() {
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }

    if (rv > -1) {
        return rv;
    }
    else {
        return 0;
    }
}

So what you can do with this is:

if(getInternetExplorerVersion() == 6) {
    $('head').append('<link id="styles" rel="stylesheet" type="text/css" href="/ie6Styles.css" />');
}

Or something along those lines.


Other Solutions: For other browsers you can also do the following:

var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
var is_explorer = navigator.userAgent.indexOf('MSIE') > -1;
var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
var is_safari = navigator.userAgent.indexOf("Safari") > -1;
var is_Opera = navigator.userAgent.indexOf("Presto") > -1;
var is_Silk = navigator.userAgent.indexOf("Silk") > -1;
var is_Kindle = navigator.userAgent.indexOf("Kindle") > -1;

and I prefer these for iPads/iPods/iPhones:

if (navigator.userAgent.match(/iPad/)) { iPad = true; }
if (navigator.userAgent.match(/iPhone/) || navigator.userAgent.match(/iPod/)) { iPhone = true; }

Modernizr works great, but it only lets you know if a browser can handle certain features. Sometimes you actually have to target a specific browser for other fixes, like styles. This is where any of the above solutions can come in really handy. Good luck and let me know if you have any questions.

Termato
  • 1,556
  • 1
  • 16
  • 33
  • 1
    For IE 8 and later, it is better to check for Trident no? – Q-B Aug 29 '14 at 18:44
  • Absolutely. In this scenario though, I'm checking the `appName` and not the `userAgent` for the first if statement. If you are checking the UserAgent, Trident and/or MSIE would both work. Here is the userAgent output for IE10: **Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; Touch)** So, in that respect, yes. :) – Termato Aug 29 '14 at 19:15
  • 1
    yes, but IE11 no more use MSIE ;) (since I don't use IE, I found it here: http://fr.wikipedia.org/wiki/User-Agent) – Q-B Aug 30 '14 at 09:22
0

You can opt for some sort of JavaScript detection, but that would be beating around the bush and not dealing with the problem directly. It is what's usually called a band aid fix.

You shouldn't have to use hacks for IE11, IE10 and even IE9. They are fairly competent and standards compliant browsers.

I would look into solving the issues at their core - clean up and simplify your markup, make sure it validates, all tags are closed, declare dimensions, use a CSS reset, clear your floats etc.

That's if your issues are layout related.

If they aren't and you are using some bleeding edge functionality that's not supported everywhere, use feature detection - not browser detection.

This is the exact reason why Microsoft stopped supporting conditional comments. This is also why they changed the User Agent in IE11 to completely omit the fact that the browser is in fact IE.

They did it to encourage proper feature detection i.e Modernizr and not UA sniffing, as it's a bad idea.

senectus
  • 409
  • 4
  • 14
  • IE doesn't always render everything properly in all of its versions. Sometimes, you need to target a specific version and implement a very specific style in order to target how it renders things. You do make a great statement that any feature based problems should be handled by Modernizr and I back that statement up 100%. I just think that some problems, like some browser rendering issues, can't all be solved with perfect HTML. I'm only saying that because I've had some experiences where having to target a specific browser using JavaScript was my only solution. – Termato Aug 29 '14 at 18:35
  • 1
    Of course not every layout issue can be solved with perfect markup, but the vast majority can, especially if you only have to support IE9 and up. It's acceptable to target a specific browser if there is a known bug in the way that browser renders a particular feature. If you use feature detection in that scenario, it will come back as positive as the browser will indeed support that feature, but there would be some quirks with the rendering. Plenty of such examples with – senectus Aug 29 '14 at 18:44
  • I think were on the same page. Good stuff. :) – Termato Aug 29 '14 at 19:12