How do I detect if the browser supports HTML5 data
attribute using Modernizr?
Asked
Active
Viewed 1,907 times
4

Diogo Cardoso
- 21,637
- 26
- 100
- 138
1 Answers
6
Test whether an element has the property dataset
.
Modernizr.addTest('data', function () {
var elem = document.createElement('div');
return !!elem.dataset;
});

Rich Bradshaw
- 71,795
- 44
- 182
- 241
-
5`!!` just ensures that the value returned is either `true` or `false`, rather than, say, `undefined` which evaluates to `false` or `function(){/* code */}`, which evaluates to `true` when treated as a boolean. – cmptrgeekken Jun 04 '11 at 22:05
-
1Yep. In an unsupporting browser elem.dataset = undefined. !undefined = true. !true = false. So !!elem.dataset returns false in an unsupported browser. In a supported one it returns a DOMStringMap, which is a not a falsy value. ! that = false, !false = true. – Rich Bradshaw Jun 04 '11 at 23:08
-
@Rich How do you put this into use in `if` statement? In other words I want to perform an action if this is true and another if it is false. Do you do that inside or outside the `.addTest` function? – ryanve Aug 13 '11 at 16:33
-
1Run that first, then it will make the variable Modernizr.data, which is a boolean. It also adds the class "data" to the html element, for CSS, if needed. – Rich Bradshaw Aug 13 '11 at 20:19