PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » JavaScript » Add Data Attribute of User Agent

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:

<html
	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)"
	data-platform="Win32">
	...

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"] {
  ...
}

Reference URL

Subscribe to The Thread

  1. Conor Haining

    This one is very useful!

  2. 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:

    <html>
        ...
    

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

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

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

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

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~