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 acplish something like this:
if ($('.item[data-index="' + indexVal + '" ]'){
//if an .item with the data-index value of indexVal exists...
}
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 acplish something like this:
if ($('.item[data-index="' + indexVal + '" ]'){
//if an .item with the data-index value of indexVal exists...
}
Share
Improve this question
edited Nov 17, 2015 at 15:36
Brian Tompsett - 汤莱恩
5,89372 gold badges61 silver badges133 bronze badges
asked Aug 29, 2013 at 19:20
mheaversmheavers
30.2k62 gold badges198 silver badges326 bronze badges
1
- appending [0] will Boolean the jQuery hits, just like .length>0 or just .length if in an if() statment... – dandavis Commented Aug 29, 2013 at 19:43
4 Answers
Reset to default 8missing )
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) {
try this:
if ($('.item[data-index="' + indexVal + '" ]').length > 0){
}
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){
}
$('.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('*')