Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data key name from data attribute?

Tags:

jquery

I want to get key name from my html element?

Sample code :

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

Using jquery data method I am able to key value but I want to extract key name?

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


var keyName=?????
like image 860
Nidhi Avatar asked Dec 21 '22 05:12

Nidhi


2 Answers

You can access all data keys and values this way:

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

HERE is the example.

like image 91
kubetz Avatar answered Jan 06 '23 09:01

kubetz


data-code would be the key for that.

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

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]
like image 43
Jasper Avatar answered Jan 06 '23 10:01

Jasper