Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find data attribute by part of name

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

like image 219
user348173 Avatar asked Oct 21 '22 17:10

user348173


2 Answers

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/

like image 155
techfoobar Avatar answered Oct 31 '22 11:10

techfoobar


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

like image 31
gdoron is supporting Monica Avatar answered Oct 31 '22 11:10

gdoron is supporting Monica