Reputation: 30158
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
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
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
Reputation: 1048
try this:
if ($('.item[data-index="' + indexVal + '" ]').length > 0){
}
Upvotes: 5
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