Micah
Micah

Reputation: 4560

js, find / match/ search if element stored data by data name

I want to find out whether if a element has stored specific data.

For example, if a element has a data and the name called DATA + etc.

$el.data('DATA' + 'etc', value);

If I only know the name will be DATA + something but I dont know what is the something.

How can i find out / search / match if the element has data and its name started with 'DATA'.

alert($el.data('DATA') ? 'Yes' : 'No')

Thank you very much for your advice.

Upvotes: 1

Views: 151

Answers (2)

bobber205
bobber205

Reputation: 13372

Store a object for the 'DATA' key. Then add your etc property onto that object.

A check can be done by writing

'propertyName' in object

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359966

.data() with no arguments gets you an object of the attached data, so you can iterate over the keys to see if any of them start with 'DATA'.

var hasMatchingData = false;
var allData = $el.data();
for (var key in allData) {
    if (allData.hasOwnProperty(key) && key.match(/^DATA/g)) {
        hasMatchingData = true;
        break;
    }
}
alert(hasMatchingData ? 'Yes' : 'No')

Upvotes: 2

Related Questions