Search code examples
jqueryinternet-explorerremoveclassnavigator

What is the proper jQuery Syntax for removing a class based upon a visitor's brand web browser?


I am wanting to remove a class from a specified ID if a visitor is using Internet Explorer (IE).

At first, I created a redirect for visitors using IE with the following JavaScript syntax, and it worked just fine:

<script language=javascript>
if ((navigator.userAgent.match(/IE/i))) {
    document.location = "http://www.somepage.com/IE_page.html";
    }
</script>

But I want to take a different tack. Rather than redirect to another page, I want the ability to remove (or add perhaps) class(es) to ID's.

What I created, but hasn't worked, was this:

<script language=javascript>
if ((navigator.userAgent.match(/IE/i))) {
    $('#someIdHere').removeClass('someClassHere');
    }
</script>

I have the requisite jQuery link above this script.

What syntax am I missing with this jQuery statement?


Solution

  • You need to wrap the code in a $(document).ready() block, or the #someIdHere element won't exist on the page when your code executes.

    $(document).ready(function () {
        if ((navigator.userAgent.match(/IE/i))) {
            $('#someIdHere').removeClass('someClassHere');
        }
    });
    

    .. alternatively, you can include your code at the bottom of the page (before the </body>) rather than in the <head>.

    Also note that you run the risk of matching non-IE browsers with your regex pattern. Something like /\bMSIE\b/i would be more precise.


    FWIW, see HTML Script tag: type or language (or omit both)? with regard to using language=javascript in <script /> tags.