Find data attribute by name

How can I get the value of a data attribute by name?
For instance:

<div data-pcp-email="some text" data-pcp-order="some int" data-ref="some data"></div>

And suppose I want all data attributes to start with data-pcp-: the result should be data-pcp-emailanddata-pcp-order

+5
source share
3 answers

You can get all the attributes (and their values) in which the creature creature names have "pcp", as shown 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 is a demo: http://jsfiddle.net/8waUn/1/

+4
source

If you set the attribute using only HTML or using the jQuery function attr:

$('div[data^=pcp-]')

If you set the value using jQuery function data, you will need to use filter.

$('div').filter(function(){
    var data = $(this).data();
    for (var key in data){
        return key.indexOf('pcp-') === 0;

    }
});

, 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

+1

" " jQuery:

$('div[data^=pcp-]')
-2

All Articles