My goal is to add some jQuery to a project that will check to see if an element has a data-attribute
without a value. For instance, with the video
tag you can just add autoplay
without a value and it will autoplay. I am attempting to do the same thing and wondering if it is possible. Here's what I tried, but it's returning false currently:
$(function() {
$('div').click(function() {
if ($(this).attr('data-specs')) {
console.log('has specs');
} else {
console.log('no specs');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-specs>Specs</div>
Through jQuery you can use the .is(selector)
method.
So if you set the selector to an attribute one, you can do your check
$(function() {
$('div').click(function() {
if ($(this).is('[data-specs]')) {
console.log('has specs');
} else {
console.log('no specs');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-specs>Specs</div>
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