7

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...
}
1
  • appending [0] will Boolean the jQuery hits, just like .length>0 or just .length if in an if() statment... Commented Aug 29, 2013 at 19:43

4 Answers 4

8

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) {
Sign up to request clarification or add additional context in comments.

Comments

5

try this:

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

}

Comments

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){
}

Comments

0

$('.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('*')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.