How can I detect with jQuery / JavaScript, if a given data-*
Attribute of a certain DOM element has an empty string as a value? Common comparison operators do not seem to work properly, as the example below shows. I
May be close to: Checking for HTML5 data attribute with no value or set data- html5 value by default
But none of these answers matched this issue.
The HTML
<ul class="list">
<li class="list--item" data-id="x6gftcc-44">First entry</li>
<li class="list--item" data-id="">Last entry</li>
</ul>
<div class="message"></div>
Some CSS
.list{
list-style-type: none;
}
.list--item{
display: inline-block;
min-width: 200px;
padding: 20px;
border: 1px solid rgb(60,64,73);
cursor: pointer;
}
.message{
display: none;
}
.message.active{
display: block;
}
.true{
color: green;
}
.false{
color: red;
}
The JavaScript
$(document).ready(function(){
$('.list--item').click(function(event, target){
function hasId(){
if ($(this).data('id') != ''){
return true;
}
else{
return false;
}
};
var entry = {
id: $(this).data('id'),
hasId: hasId()
};
if (entry.hasId){
$('.message').addClass('active true');
$('.message').text('Picked entry ID: ' + entry.id);
}
else{
$('.message').addClass('active false');
$('.message').text('Entry ID not available');
}
})
});
Example available at CodePen.
data
unless you're really using it for what it's meant to be used for. If you're just accessing the attribute vaule, useattr
.data
is not just an accessor fordata-*
attributes, it does much more than that, and has overhead. – Exerciserdata-*
attributes. It's for managing jQuery's internal data store, which it will cause to be initialized (only) fromdata-*
attributes. Using it as an accessor just to get the attribute value is not correct usage, and makes jQuery do extra work and consume extra memory. It also leads to confusion, sincedata
never setsdata-*
attributes. – Exerciser