1

How can I check the existence of an element in jQuery?

Currently snip of my code looks like this:

if ($(selector).length>0) {
    // This should do something
}

Is there some kind of function, or a plugin that could work with this? Is there any better way to approach this?

Cod3r-b0ss
  • 205
  • 1
  • 10
  • 1
    What's wrong with your current approach? – Mayank Pandeyz Apr 24 '17 at 06:34
  • 1
    if `$(selector).length` is 0, then it means that there are no elements that matches the provided `selector` value. So if you pick `$(.foo)` and its length is 0, then there are no elements with such class name. – KarelG Apr 24 '17 at 06:35
  • @MayankPandeyz The code is not self documenting or self-explanatory. I completely understand why this question is being asked. The code just so happens to do what OP wants. If you wanted to know if your friend has a girlfriend, would you ask them "Is your girlfriend taller than 0cm?" – ESR Apr 24 '17 at 06:58
  • @TahaPaksu "Possible duplicate" more like "exact duplicate" – Mikey Apr 24 '17 at 07:16
  • Yea I know, that's an auto comment in SO when you flag the post as duplicate ;) – Taha Paksu Apr 24 '17 at 07:17

0 Answers0