Jitender
Jitender

Reputation: 7971

jquery if condition?

i want to take out two result when condition is true so i made small function for it but only first result is appearing when condition is true. i set height and width attribute because when src is blank ie display image frame and if i leave height and width attribute blank ie taking height and width 1 px.

$(function () {

    if ($('img.offerProduct').attr('src') == false) {
        $('.offerProduct').removeClass('offerProduct');
        $('.offerProduct').attr({width:'0', height:'0'})


    }
}

)


<body>

<img src="" width="60" height="60" class="offerProduct" />
</body>

Upvotes: 0

Views: 53

Answers (2)

danwellman
danwellman

Reputation: 9253

The attr() method only gets the attribute of the first element in the matched set. To process all images with the class offerProduct, you should use the each() method:

$(function () {

    $('img.offerProduct').each(function() {
        if($(this).attr('src') == false) {
            $('.offerProduct').attr({width:'0', height:'0'}).removeClass('offerProduct')
        }
    }
});

Upvotes: 3

Rody
Rody

Reputation: 2655

You are removing the class "offerProduct" from the image element. And in the line below you are setting the attributes on the element with the class "offerProduct", which you just deleted. So the second selector will return an empty object.

You can better use chaining of your jquery commands:

 $('.offerProduct').removeClass('offerProduct').attr({width:'0', height:'0'})

See working example at: http://jsfiddle.net/assZV/

But, maybe it's better to just remove the entire element when the image does not exists? you can use the attribute selector to immediately find each image without src:

$(function () {
    $('img.offerProduct[src=""]').hide();
});

Upvotes: 1

Related Questions