220 ...">

How to get data key name from data attribute?

I want to get the key name from my html element?

Code example:

 <td data-code="123">220</td>

Using the jquery data method I can use the key value, but want to extract the key name?

var keyValue=$("td").data("code"); //123


var keyName=?????
+3
source share
2 answers

there will be a data key for this.

If you want to get keys for unknown key / value pairs, you can use a loop for (var key in data) {}:

var all_values = [],
    data       = $('td').data();
for (var key in data) {
    all_values.push([key, data[key]]);
}
//you can now access the key/value pairs as an array of an array

//if $(td).data() returns: `{code : 123}` then this code would return: [ [code, 123] ]
//you could get the first key with: all_values[0][0] and its corresponding value: all_values[0][1]
+2
source

You can access all keys and data values ​​this way:

$.each($("td").data(), function(key, value) {
  console.log(key + ": " + value); 
});

HERE is an example.

+7
source

All Articles