0

I've been trying to make my if statement work, but I cannot find the solution. Thanks.

<div class="imgContain">
    <img class="finalimg" alt="link" src="website.com/imga546.jpg">
    <img class="finalimg" alt="green" src="website.com/imga645.jpg">
    <img class="finalimg" alt="cap" src="website.com/imga6786.jpg">
    <img class="finalimg" alt="sarge" src="website.com/imga31234.jpg">
</div>

Pseudo-code

jQuery if(something = to any of my alt attributes){do...}
//altattr is equal to an attribute that may match the alt attribute

ex: if('link' == $('img[class="finalimg"]').attr('alt'))

 if(altattr == $('img[class="finalimg"]').attr('alt')){
        //do stuff
        }

I have to select the class imgContain first to make this work right? I know that this will only work on my first element, but I'm trying to make the if statement work first.

0

4 Answers 4

1

You're too hung up on fixing the if statement when you don't even need one.

$('.finalimg[alt="link"]').doSomething();

or

$('.finalimg[alt="link"]').each(function(){
    // do something with this...
    $(this).doSomething();
});

and to use a variable in place of "link", use string concatenation.

$('.finalimg[alt="' + altattr + '"]').doSomething();
Sign up to request clarification or add additional context in comments.

Comments

0

This will loop through all images with the class finalimg and once it's found one matching (in this case the last img) the altattr variable it will alert.

var altattr = 'sarge';

$("img[class='finalimg']").each( function(index, element){
    if(altattr == $(this).attr('alt')){
        alert("found");
    }
});

Comments

0

You can try select the image with the specified alt attribute if there aren't any length will be zero.

if($('img[class="finalimg"][alt="' + altattr +  '"]').length > 0){
        //do stuff
}

This would be equivalent using class selector:

if($('img.finalimg[alt="' + altattr +  '"]').length > 0){
        //do stuff
}

DEMO

Comments

0

Have a look at this - http://jsfiddle.net/jayblanchard/m4Lk6/

if(0 !=  $('img[class="finalimg"][src="website.com/imga546.jpg"]').length) {
    $('body').append('<div>I found the image!</div>');
}

Here i am testing for the existence of an image element that has the proper class and source. If it exists its length will be 1, if not it will be 0.

EDIT: made a change based on the fact that the selector could return a number greater than one if there were multiples of these in the page.

2 Comments

well, more precisely, it won't be 0 if it exists. It could be greater than one if there are multiple. little nitpicky tho
Ah - true. I was just thinking with the current set of HTML that the OP provided.

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.