How can I get a value of data attribute by part of name?
For example:
<div data-pcp-email="some text" data-pcp-order="some int" data-ref="some data"></div>
And suppose, I want to get all data attributes begin with data-pcp-
: the result must bedata-pcp-email
and data-pcp-order
You can get all the attributes (and their values) where the attribute name beings with 'pcp' like below:
// get an object map containing all data attributes
var data = $('selector').data();
// filter out what you need
for(var key in data) {
if(key.indexOf('pcp') === 0) { // attrib names begins with 'pcp' ?
console.log(key + ' => ' + data[key]);
}
}
Here's a demo: http://jsfiddle.net/8waUn/1/
If you only set the attribute with the HTML or with jQuery attr
function:
$('div[data^=pcp-]')
If you set the value with jQuery's data
function, you will have to use filter
.
$('div').filter(function(){
var data = $(this).data();
for (var key in data){
return key.indexOf('pcp-') === 0;
}
});
If you want only the attributes you can use map
:
var values = $('div').map(function () {
var data = $(this).data();
var results = [];
for (var key in data) {
if (key.indexOf('pcp') === 0) results.push({
key: key,
value: data[key]
});
}
if (results.length)
return results;
}).get();
console.log(JSON.stringify(values));
Live DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With