jQuery convert data-* attributes to lower camel case properties

html, javascript, jquery

Solution

I would use a for..in loop to read the data-* tags.. Also you don't need to camelcase as jQuery converts it to camelCase internally... Source code reference.

$('.poshytip-trigger').each(function (index) {
    var $this = $(this);
    var data = $this.data();
    var options = {};

    for (var keys in data) {
        options[keys] = data[keys];            
    }

    // For older versions of jQuery you can use $.camelCase function
    for (var keys in data) {
        options[$.camelCase(keys)] = data[keys];
    }

});

DEMO

for jQuery 1.4.4,

$('.poshytip-trigger').each(function(index) {
    var $this = $(this);
    var data = $this.data();
    var options = {};

    for (var keys in data) {
        options[camelCase(keys)] = data[keys];
    }
});

//copied from http://james.padolsey.com/jquery/#v=git&fn=jQuery.camelCase
function camelCase(str) {
    return str.replace(/^-ms-/, "ms-").replace(/-([a-z]|[0-9])/ig, function(all, letter) {
        return (letter + "").toUpperCase();
    });
}

DEMO for 1.4.4

Problem

I have the following jQuery script to intialise a jQuery plugin called poshytips. I want configure the plugin using Html5 data attributes. I am repeating myself big time, can anyone come up with a better way to do this? ``` $('.poshytip-trigger').each(function (index) { var $this = $(this); var data = $this.data(); var options = {}; if (data['class-name']) { options.className = data['class-name']; } if (data['align-x']) { options.alignX = data['align-x']; } if (data['align-y']) { options.alignY = data['align-y']; } if (data['offset-y']) { options.offsetY = data['offset-y']; } if (data['offset-x']) { options.offsetX = data['offset-x']; } $this.poshytip(options); }); ```

Original source