mheavers
mheavers

Reputation: 30158

Check for existence of specific data attribute value

I'm trying to select a DOM element with a specific attribute value. I'd like to avoid an each() loop, but all I've seen in jQuery is the ability to detect the existence of the data attribute, not its value. So, I want to accomplish something like this:

if ($('.item[data-index="' + indexVal + '" ]'){
  //if an .item with the data-index value of indexVal exists...
}

Upvotes: 7

Views: 13388

Answers (4)

Raphael Ribeiro
Raphael Ribeiro

Reputation: 539

$('.item[data-index]').length > 0

if you searching for specific value, you can insert the value in "" :

$('.item[data-index="123"]').length > 0

or

$('.item[data-index]').is('*')

Upvotes: 0

Moazzam Khan
Moazzam Khan

Reputation: 3170

missing ) and $(selector) should not be put in a if condition. it is always true even it does not select anything.

if ($('.item[data-index="' + indexVal + '" ]').length) {

Upvotes: 8

sd1sd1
sd1sd1

Reputation: 1048

try this:

if ($('.item[data-index="' + indexVal + '" ]').length > 0){

}

Upvotes: 5

Michał Szałapski
Michał Szałapski

Reputation: 331

should be

if ($('.item[data-index="' + indexVal + '" ]')){
  //if an .item with the data-index value of indexVal exists...
}

or

if(jQuery('.item').attr('data-index') == indexVal){
}

Upvotes: 0

Related Questions