Verify if an element exists using jQuery
- August 1st, 2010
- Posted in articles
- By Ionut
- Write comment
A common and sometimes overlooked question is how to verify if a DOM element exists using jQuery. This can be done very easy using the length property:
-
if (!$('#example').length)
-
alert("Element not found");
So.. if the length property is larger than 0 then the element exists. A common mistake that people tend to do is to use !$(‘#example’), but this is wrong because jQuery will return an object even when not finding the requested DOM element.
interesting, thanks