You'll be glad to hear the DOM has basically done this work for you, and along the way it's removed the data
prefix and converted kebab-case
to camelCase
, etc. It's done that via the dataset
property, which is a DOMStringMap
:
$(".trData").click(function () {
for (const [name, value] of Object.entries(this.dataset)) {
// Here, `name` will be `"a"`, `"b"`, `"c"`, etc., and value will be `"1"`, `"2"`, `"3"`, etc.
// Note that the values have been magically converted to numbers for you
console.log(`${name} = ${value}`);
}
});
Live Example:
$(".trData").click(function () {
for (const [name, value] of Object.entries(this.dataset)) {
// Here, `name` will be `"a"`, `"b"`, `"c"`, etc., and value will be `1`, `2`, `3`, etc.
// Note that the values have been magically converted to numbers for you
console.log(`${name} = ${value}`);
}
});
<div class="trData" data-a="1" data-b="2" data-c="3" data-d="4">click me</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you don't want the automatic conversion that dataset
does, you can use attributes
and filter out the non-data-*
attributes:
$(".trData").click(function () {
const dataAttrs = Array.from(this.attributes)
.filter(attr => attr.name.startsWith("data-"))
.map(attr => [attr.name.substring(5), attr.value]);
for (const [name, value] of dataAttrs) {
// Here, `name` will be `"data-a"`, `"data-b"`, `"data-c"`, etc., and value will be `"1"`, `"2"`, `"3"`, etc.
// Note that the values are *strings*
console.log(`${name} = ${value}`);
}
});
Live Example:
$(".trData").click(function () {
const dataAttrs = Array.from(this.attributes)
.filter(attr => attr.name.startsWith("data-"))
.map(attr => [attr.name.substring(5), attr.value]);
for (const [name, value] of dataAttrs) {
// Here, `name` will be `"data-a"`, `"data-b"`, `"data-c"`, etc., and value will be `"1"`, `"2"`, `"3"`, etc.
// Note that the values are *strings*
console.log(`${name} = ${value}`);
}
});
<div class="trData" data-a="1" data-b="2" data-c="3" data-d="4">click me</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>