web design and coding services with a huge twist of creativity.

jQuery tip: Check if an element exists

Published 1 year ago in Blog, Web

It’s a very common question for people starting out with jQuery: How do I know if element X exists? There is no standard function for you to use, however, it’s really simple to write one yourself.

What you’ll probably try to do first is to perform a check on a jQuery object, like this:

//This won't work :(
if ( $("#myId") ) {
  //awesome code here
}

The reason this method doesn’t work is that when you use the $(), you’re asking for a jQuery object. You always get a jQuery object, even if it’s an empty one. Thus, the above code always returns true, and that’s just sad.

However, the object returned by jQuery will have an internal array filled with all the elements that do match your selector. You can access this internal list’s length using the .length property. This means that, if the length of your object is greater than zero, your element does indeed exist in the DOM. Putting that into code, we get:

//This works, yay!
if ( $("#myId").length > 0 ) {
  //awesome code here
}

Although the examples shown here only checked for the existence of an element with a certain ID attribute, you can obviously use this technique with any jQuery selector you wish.

one person thinks:

  1. Just what i looking for! thanks!i fight with jquery for a couple of hours haha, nice tip Bruno

drop me a line!

If your comment doesn't appear immediately after you submit it, it might be held for moderation. Sorry, all you can do is wait.

You can use these elements to write your comment.