Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming Convention For Data Attribute Value When Used Specifically for Javascript

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.

like image 785
Neil Avatar asked Apr 27 '26 15:04

Neil


1 Answers

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 letter a to z, 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 a to z (before the transformation);
  • a prefix data- is added;
  • any ASCII uppercase letter A to Z is 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-def corresponds to the key abcDef.

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>
like image 54
Scott Marcus Avatar answered Apr 29 '26 04:04

Scott Marcus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!