There are some subtleties to jQuery that still confuse me, compared to how traditional JavaScript acts at least.
With traditional JavaScript, you could check for “an element”. The simplest example would be getting an element by ID.
Say for example, we had an element with the ID “test”
1 |
<div id="test">Some Content</div> |
We could use traditional JavaScript like so:
1 |
if(document.getElementById('test')){ |
In jQuery however, you cannot use:
1 |
if($('#test')){ |
jQuery will always return an object. Therefore the if statement will always be true and never false. If the element doesn’t exist, jQuery will return an empty object, but an object nonetheless. This, however, leads to the solution. Using jQuery, we can check that the object returned is empty, or has a “size”.
1 |
if ($("#test").length > 0){ |
Image Credit: Wonderlane
Comment or tweet @douglasradburn