Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if data attribute exists without a value

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>
like image 773
APAD1 Avatar asked Feb 23 '17 22:02

APAD1


1 Answers

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>
like image 58
Gabriele Petrioli Avatar answered Sep 17 '22 14:09

Gabriele Petrioli