Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to check for particular .data() value in a jQuery object?

Tags:

jquery

I'd like to check to see if a jQuery data value has been applied to an object. For instance, code elsewhere may assign data to an object:

$myObject.data('hello','world');

Elsewhere, I want to check to see if a value was given to the data property hello.

What is the proper way to handle this? .hasData seemed like the obvious choice but appears to not work like 'hasClass' does in that you can't seem to pass a particular data element name to it.

like image 276
DA. Avatar asked Apr 27 '12 22:04

DA.


2 Answers

Check if the data exists and set it if not.

if ($myObject.data('hello') === undefined) {
    // data NOT set
    $myObject.data('hello','world');
} else {
    // data IS set
}
like image 113
BeatnikDude Avatar answered Sep 30 '22 19:09

BeatnikDude


To obtain the property (e.g. for comparison), use .data with one argument:

$myObject.data('hello')

It returns the undefined value when the data does not exists.

like image 20
Rob W Avatar answered Sep 30 '22 19:09

Rob W