I'm a total noob in the web arena, I've been learning jQuery lately. My concern is, will I be able to access the 'data' attribute using jQuery from my HTML if my browser does not support HTML5?
Asked
Active
Viewed 1,088 times
4
-
1As far as i am concerned you can use the data attribute of html 5 in any browser, I know that even Internet Explorer should have now issue, because IE ignores all the attributes it does not know how to render or use. See this post http://stackoverflow.com/questions/2412947/do-html5-custom-data-attributes-work-in-ie-6 – jacqijvv Mar 17 '12 at 10:38
3 Answers
8
Yes, you can use the data attribute and you will be able to access it with jQuery even if the browser doesn't support HTML5:
var value = $('#foo').data('value');
where you have:
<div id="foo" data-value="bar">Baz</div>
The only thing is that the data
attribute is not valid if your DOCTYPE is not HTML5 => if you try to use it in HTML 4.01 Transitional for example the validator will cry but your site will work without issues.

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
1
You could use .attr
to access it like:
$(your_selector).attr('data-foo');

xdazz
- 158,678
- 38
- 247
- 274
-
1Could, but should not, especially when manipulating the data rather than reading them. With `attr()`, the data goes back into the DOM. With `data()`, it is kept separately. If you change a value with `attr()`, then read it with `data()` you will get different values. Also `attr()` deals with strings only, `data()` will convert to native types, like integers. Whatever you do, don't mix use of `attr()` and `data()` unless you really know what you're doing. My rule of thumb is to use `attr()` for reading original DOM metadata or changing DOM properties and using `data()` for application state. – Steven Don Mar 17 '12 at 10:44
1
yes.
but if your browser does not suport HTML5, the data
-attribute is not valid (X)HTML. However, this should not be a problem for accessing the data with jQuery.

Alex
- 6,276
- 2
- 20
- 26