Why is my .data() function returning [ instead of the first value of my array?

It’s treating your variable as a string, the zeroth element of which is [.

This is happening because your string is not valid JSON, which should use double-quotes as a string delimiter instead of single quotes. You’ll then have to use single-quotes to delimit the entire attribute value.

If you fix your quotation marks your original code works (see http://jsfiddle.net/ktw4v/12/)

<div data-stuff="["a","b","c"]"> </div>

var stuff = $('div').data('stuff');

When jQuery sees valid JSON in a data attribute it will automatically unpack it for you.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)