dash-style
to camelCase
conversion
A custom data attribute name is transformed to a key for the DOMStringMap
entry by the following:
A
to Z
);data-
(including the dash);U+002D
) followed by an ASCII lowercase letter a
to z
, remove the dash and uppercase the letter;camelCase
to dash-style
conversion
The opposite transformation, which maps a key to an attribute name, uses the following:
a
to z
;data-
prefix;A
to Z
, then lowercase the letter;For example, a data-abc-def
attribute corresponds to dataset.abcDef
.
element.dataset.keyname
.element.dataset['keyname']
.in
operator can check if a given attribute exists: 'keyname' in element.dataset
. Note that this will walk the prototype chain of dataset
and may be unsafe if you have external code that may pollute the prototype chain. Several alternatives exist, such as Object.hasOwn(element.dataset, 'keyname')
, or just checking if element.dataset.keyname !== undefined
.When the attribute is set, its value is always converted to a string. For example: element.dataset.example = null
is converted into data-example="null"
.
To remove an attribute, you can use the delete
operator: delete element.dataset.keyname
.
A DOMStringMap
.
<div id="user" data-id="1234567890" data-user="carinaanand" data-date-of-birth>
Carina Anand
</div>
const el = document.querySelector("#user");
// el.id === 'user'
// el.dataset.id === '1234567890'
// el.dataset.user === 'carinaanand'
// el.dataset.dateOfBirth === ''
// set a data attribute
el.dataset.dateOfBirth = "1960-10-03";
// Result on JS: el.dataset.dateOfBirth === '1960-10-03'
// Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand" data-date-of-birth="1960-10-03">Carina Anand</div>
delete el.dataset.dateOfBirth;
// Result on JS: el.dataset.dateOfBirth === undefined
// Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand">Carina Anand</div>
if (el.dataset.someDataAttr === undefined) {
el.dataset.someDataAttr = "mydata";
// Result on JS: 'someDataAttr' in el.dataset === true
// Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand" data-some-data-attr="mydata">Carina Anand</div>
}
Specifications Browser compatibility
Loadingâ¦
See alsodata-*
class of global attributesElement.getAttribute()
and Element.setAttribute()
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4