Add Data Attribute of User Agent

var b = document.documentElement;
b.className = b.className.replace('no-js', 'js');
b.setAttribute("data-useragent",  navigator.userAgent);
b.setAttribute("data-platform", navigator.platform );

Which results in data attributes being added to the html element like:

	data-useragent="Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)"

Which allows you to be able to target very specific browsers on very specific platforms with CSS:

html[data-useragent*="Chrome/13.0"][data-platform="Win32"] {

This was referenced from a post by Rogie King that has since gone offline.


  1. Conor Haining
    Permalink to comment#

    This one is very useful!

  2. Jan-Marten
    Permalink to comment#

    Damn, that is helpfull. And it’s a hell lot better SEO than the IE specific if statements in your HTML markup. The only thing you need to keep in mind is that this will only work on CSS that gets loaded after that specific bit of JavaScript runs. It’s also not completely bulletproof, since there’s no solid fallback or browsers that don’t support data attributes, although you might be forcing them on the elements this way, even in older browsers.

    What Googlebot should see when he looks at this page:


    What your CSS gets to see is the same as Chris shows above.

    • Jimmy Rittenborg
      Permalink to comment#

      So Google developers actually promotes hell bad SEO – interesting stuff.

  3. Mathias Bynens
    Permalink to comment#

    WTF. Don’t use user-agent sniffing when feature testing can be used instead.

    • Chris Coyier
      Permalink to comment#

      Read Rogie’s article at the Reference URL. Feature testing, while obviously better, wouldn’t have helped him there.

  4. Sridhar
    Permalink to comment#

    It is really very useful. Is that CSS will work in all browsers?

  5. Eric
    Permalink to comment#

    Will not work in IE6. I asked the folks at HTMLDoctor about styling data-elements.

  6. Bryan Chalker
    Permalink to comment#

    I believe the uber-geek Rogie has the reference post here now:

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

We have a pretty good* newsletter.