Check if a div exists with jquery
To quickly check if a div
exists in jQuery, use $('#yourDiv').length > 0
. This expression evaluates to true if your div exists, and false otherwise.
Replace '#yourDiv'
with the actual ID of the div you're looking for. This one-liner is as concrete as it gets, providing an immediate yes or no answer.
Behind the scenes: working with jQuery objects
When you're commanding jQuery selectors, it helps to understand a little about "truthiness". A jQuery selector like $('selector')
will always give you a jQuery object back. Even when there are no elements matching your selector, you'll get an empty object rather than a null or undefined.
Use what's best for your code: jQuery vs Vanilla JavaScript
To avoid the overhead of jQuery when just checking presence of an ID, consider the vanilla JavaScript alternative:
This approach is just as effective and doesn't call for jQuery.
Checking for specified attributes or classes
Sometimes, in addition to just checking for existence of an element, you might want to know whether it has certain attributes or classes:
Mind the gotchas: Common pitfalls with jQuery existence checks
Remember the timing
On dynamic web pages, a maybe-now-there-maybe-now-gone div could lead you up the garden path. Always perform the existence check when the time is right in your code.
Synchronize with AJAX-ed content
If an element is getting plugged post an AJAX call, ensure your watch is ticking in sync with AJAX:
Undress does not mean absence
Visibility and existence are two different facets of a div. An element may exist in a DOM's closet but can be hidden under various cloaks (display: none
, visibility: hidden
, opacity: 0
).
Was this article helpful?