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.
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
}
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.
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