Daryl
Daryl

Reputation: 380

Why does this jquery not work?

$(function () {

    if($('body').find('#slideshow')) {
        $('body').find('.topBox').addClass('home');   
    }

});

I mean it works, but if i take out #slideshow it will still add the class?

I tried else remove class.

Upvotes: 0

Views: 166

Answers (3)

Daniel
Daniel

Reputation: 890

if($('body').find('#slideshow')) {}

will always evaluate as true. $('body').find('#slideshow') does return something: an object (even if its an empty object). Instead, test the length of the object:

if($('body').find('#slideshow').length) {}

Upvotes: 1

Quentin
Quentin

Reputation: 943569

The return value from jQuery('body').find(...) will always be true as it returns a jQuery object.

You want to check if it returns any elements that match, so you want:

if(jQuery('body').find(...).size())

Upvotes: 1

rahul
rahul

Reputation: 187040

If you want to check the existence of an element then you can use .length property for that element selector.

What about this code

if ($("#slideshow").length > 0)
{
    $('.topBox').addClass('home'); 
}

Upvotes: 2

Related Questions