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.


