Devesh Chauhan
Devesh Chauhan

Reputation: 411

How to check same class having same attribute with unique value

I have few same class elements having same attribute with unique value, like

<div class="myclass" data="1"></div>
<div class="myclass" data="2"></div>
<div class="myclass" data="3"></div>
<div class="myclass" data="4"></div>

Is there a way to check condional like

if($('.myclass').hasAttr('data').hasVal('2'))
// want to do something

Upvotes: 0

Views: 55

Answers (2)

Amit Joki
Amit Joki

Reputation: 59252

Yes there is. It's called $.fn.is

if($('.myclass').is('[data=2]'))
  // do something 

I would suggest against the use of custom attributes that do not adhere to the spec. So, just use data-api attributes. Something like below

<div class="myclass" data-num="1"></div>
<div class="myclass" data-num="2"></div>

and if($('myclass').is('[data-num=2]')){}

Upvotes: 4

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can get the element by data value using jquery and then use the returned length as condition in if statement:

if($('.myclass[data=2]').length)
    //do something

Demo

Upvotes: 1

Related Questions