Category: ‘Javascript’
How to tell if an HTML element exists using JQuery
by Jonathan on 24th Nov 2009 in Javascript
Up until now I had assumed that if i need to detect the presence of (or lack of) an element on a webpage I could simply use the following:
if($('.elementClass')) { //some code here }
but I found today that this doesn’t actually work. Whether the element exists or not you will still get a JQuery object returned, which of course equates to TRUE.
So I decided to RTFM and found that the JQuery object has an attribute, ‘length’, which returns the number of elements. So of course it will be zero if the element wasn’t found. So my code, which runs if the element is present now reads:
if($('.elementClass').length != 0) { //some code here }
Simple eh? Of course you can also say == 0 if you want some code to run if an element isn’t found.