For the Data Attribute Value, is it convention to use hyphens or camelCase?
Hyphen Example:
<input type="text" name="some_input" data-target="to-grab-input-via-javascript">
Camel Case Example
<input type="text" name="some_input" data-target="toGrabInputViaJavaScript">
A google search brings up the naming conventions on the data attribute itself, but not the naming convention on the data attribute's value. All examples I found only had one word for the data attribute value as well, so I could not find an answer to this question.
Javascript likes things camel cased, so I would imagine it should be camel cased, but I do not want to make an assumption.
There is no standard on this. Use what is most comfortable for you, but be aware that when retrieving the value with the dataset property, dashed values will be converted to camel case and vice versa:
Name conversion
dash-style to camelCase:
A custom data attribute name is transformed to a key for the DOMStringMap entry with the following rules
the prefix
data-is removed (including the dash);for any dash (
U+002D) followed by an ASCII lowercase letteratoz, the dash is removed and the letter is transformed into its uppercase counterpart;- other characters (including other dashes) are left unchanged.
camelCase to dash-style:
The opposite transformation, that maps a key to an attribute name, uses the following rules:
- Restriction: A dash must not be immediately followed by an ASCII lowercase letter
atoz(before the transformation);- a prefix
data-is added;- any ASCII uppercase letter
AtoZis transformed into a dash followed by its lowercase counterpart;- other characters are left unchanged.
The restriction in the rules above ensures that the two transformations are the inverse one of the other.
For example, the attribute named
data-abc-defcorresponds to the keyabcDef.
Here are some other examples:
console.log(document.getElementById("d1").dataset); // "data-this-is-a-test" becomes "thisIsATest"
console.log(document.getElementById("d2").dataset); // "data-thisIsATest" becomes "thisisatest"
<div id="d1" data-this-is-a-test="foo"></div>
<div id="d2" data-thisIsATest="foo"></div>
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