1

I want to add a class to an element depending on what browser they are using. This is what I have:

var browser = navigator.userAgent;

if (browser.match("Firefox")){
  $(".dollar").addClass("ff");
}

But it doesn't seem to be working. What am I doing wrong?

Edit: The HTML

<p class="dollar">$</p>
Ruby
  • 101
  • 2
  • 9

2 Answers2

0

Because navigator.userAgent returns "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"

which of course doesn't match "Firefox" in your if statement, so thus your if statement is false...

You probably want to try :

if (navigator.userAgent.search("Firefox/") > -1)

as your if - that should see Firefox - then use Chrome/ for a chrome test

[edited for if suggestion]

Roko C. Buljan
  • 164,703
  • 32
  • 260
  • 278
DoctorKraz
  • 66
  • 9
  • It matches for me. The string contains "Firefox", so I don't see why it shouldn't match. – Oriol Mar 02 '16 at 19:56
  • Thank you for your response. As what @Roko suggested, I needed the DOM to be fully loaded first. So my initial browser.match("Firefox") still works, it just needed it to be wrapped in a function. I tested out yours, it worked as well. Thank you! – Ruby Mar 02 '16 at 20:14
0

Use a document (DOM) ready wrapper:

var browser = navigator.userAgent;

jQuery(function( $ ){             // DOM is now ready

  if (browser.match("Firefox")){
    $(".dollar").addClass("ff");  // and .dollar is parsed
  }

});

Test this jsBin demo example in Firefox

Roko C. Buljan
  • 164,703
  • 32
  • 260
  • 278