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.