iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

Is there a simple/fast way to map "data-" attributes to mixed-case property names?

I have a base plugin class I use as the basis of all my jQuery plugins. It is similar to the jQuery UI widget, but does a lot more heavy lifting for me.

I now wish to map data- attribute values, from the attached element, into any options passed to the plugin. This will allow the plugin to not only take the typical options object, but also allow data-driven override values on individual elements (a common requirement).

The problem I have is that my option properties are typically mixed case e.g. MaxHeight, but apparently the HTML specification only allows lowercase characters into data- attribute names.

As an example testbed: http://jsfiddle.net/TrueBlueAussie/tfkrwq09/1/

HTML:

<div id="test" data-DataTest="test2"></div>

jQuery:

var object = {
    DataTest: 123
};
$.each($('#test').data(), function (k, v) {
    object[k] = v;
});

console.log(object.datatest); // test
console.log(object.DataTest); // 123

Desired result:

console.log(object.datatest); // undefined
console.log(object.DataTest); // test

I am after ways to map data- attributes to mixed-case properties, while retaining the current speed and simplicity (if possible).

Upvotes: 3

Views: 1201

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

See following link regarding camelCased rule: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset

So in your case, i'd use:

<div id="test" data--data-test="test2"></div>

To get:

object.DataTest; //test2

Upvotes: 1

Related Questions