DeutschEnglish

Submenu

 - - - By CrazyStat - - -

26. September 2013

jQuery: check whether an element exists

Filed under: JavaScript — Tags: , , , — Christopher Kramer @ 13:47

In traditional JavaScript, to check if some element exists, you’d have done something like this:

if(document.getElementById('someID'))

Of course this still works but what about using JQuery? So you might try this:

if($('#someID'))

But this will always be true as jQuery always returns an object, no matter whether the selector matched or not.So what you can do is the following:

if($('#someID').length > 0)

This will do the trick. You can even leave out “> 0”:

if($('#someID').length)

The cool thing is you can use this also to check more complex stuff, like whether #someID has an <img> child-element:

if($('#someID img').length)

And this is where jQuery really makes life a lot easier because with traditional JavaScript, this would be a bit lengthy for what it does.

Have fun!

Recommendation

Try my Open Source PHP visitor analytics script CrazyStat.