Gerrit Luimstra
Gerrit Luimstra

Reputation: 532

Why does this always return true? jQuery

I ran into something weird today.

This function always returns true for some reason, even if there is no title element in the given parent element.

// JSEPlaceholder contains "#adiv"
if(typeof $(JSEPlaceholder).children().find("title") !== "undefined"){
  alert();
}

Why is this happening?

Upvotes: 0

Views: 74

Answers (2)

gen_Eric
gen_Eric

Reputation: 227210

This is because jQuery will always return you a jQuery object. It may not contain any elements, but it is still an object.

What you want to do is check its length.

if($(JSEPlaceholder).children().find("title").length > 0){
    alert();
}

Upvotes: 8

Matthew Herbst
Matthew Herbst

Reputation: 31973

$.find() never returns undefined. If it finds nothing, it just returns an empty collection.

Upvotes: 4

Related Questions