I’ve been re-writing my penny auction site, NitroHawk.com, and part of the re-write is moving from the Prototype library over to the newer, more popular, jQuery. While most of my code has been easy to migrate there was one thing that threw me off for a little, checking for an element. I enjoyed the simplicity of checking for an element by using:
// checking for a div via PrototypeJS
if($('divname')){
// div exists
}
When migrating my code I the jQuery selector operator, #, in front of the object name, at attempted to use the same syntax:
// the WRONG way to check for a div in jQuery
if ($('#divname')){
// div exists
}
I quickly found out the same statement in jQuery always returns true. In the case above, an empty object will be returned with nothing in it.
Using the jQuery selector in combination with the length property you can evaluate the size of the object. As always, when evaluating you can trigger some simple logic.
if($('#divname').length > 0){
// div exists
}
This code works because jQuery returns an empty object with a length of zero, causing the if logic to evaluate to false.
Something I’ve always enjoyed with development are the various methods used to accomplish the same task. Here are a few more methods to check to see if an element exists. They all basically do the same thing by checking for the size of the object queried.
if($('#divname').length){
// div exists
}
if($('#divname).size()){
// div exists
}
if($(‘#divname’)[0]){
// div exists
}
Of course all of this could be avoided and use plain old javascript without the help of any library by using the following code to check for an element.
// plain old javascript
if(document.getElementById('divname')){
// div exists
}