We're using HTML5's data-*
attributes for some of our client side interaction set up. jQuery uses these to do its thing.
The catch is that the HTML coming in may vary. Obviously this is the problem that should be fixed but I'm not always in control of the HTML being produced, unfortunately.
The question:
Given these two tags:
<a data-sampleAttributeName="example">
<a data-sampleattributename="example">
Is there a clever way to treat them as one and the same?
The best I've come up with is something like this:
var theAttribute = ($myobject).data('sampleAttributeName');
if (($myobject).data('sampleAttributeName')){
theAttribute = ($myobject).data('sampleAttributeName')
} else {
theAttribute = ($myobject).data('sampleattributename')
}
I could turn that into a function that I could just pass the camelCase version to and check for both as well. I was just wondering if there was a cleaner built-in feature in jQuery to ignore the case of the data
(or attr
) value.
Yes, it is.
jQuery attribute value selectors are generally case-sensitive.
For both the variations given here you should get the value using
.data('sampleattributename')
The camel casing ( .data('sampleAttributeName')
) is for when the attribute is like this:
<a data-sample-attribute-name="something">Anchor</a>
Check this jsfiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With