Photo from Chile

jQuery Quickie - Checking Whether an Element Exists

I'm still a relative noob when it comes to jQuery, so today, when I had a need to check whether a particular form field existed, I had no idea how to do it. Of course some quick Googling brought me an answer, from the jQuery for Designers site by Remy Sharp.

The quick answer is that you can test the length property of any jQuery object, and if it returns zero then the element doesn't exist. For example, what I wanted to do was to disable a form field if another form field existed, so I wrote the following code:

view plain print about
1if ($("#fieldA").length != 0) {
2    $("#fieldB").attr("disabled", "disabled");
3}

Reading through the comments on that page, I saw a suggestion by Kat Reeve to add the following to a standard JavaScript include file:

view plain print about
1jQuery.fn.exists = function() { return (this.length > 0); };

Which would allow me to change the above code to:

view plain print about
1if ($("#fieldA").exists()) {
2    $("#fieldB").attr("disabled", "disabled");
3}

Nice, innit?

TweetBacks
Comments
you can actually do it even shorter without extra function:
if ($("#fieldA")[0]) {...}

Azadi
# Posted By Azadi Saryev | 5/19/10 3:57 AM
You only need:

if( $("#fieldA").length ) doSomething();

A positive integer is evaluated as true in JS.
# Posted By Dan G. Switzer, II | 5/19/10 11:28 AM
@Dan: I've seen it done both ways in JavaScript, and I used to write tests in CFML like:

if (len(myVar)) {do something}

but it was pointed out to me that that is less readable than explicitly including the comparison, and I tend to agree. However, if it's an accepted standard to leave out the comparison in JavaScript, and anyone writing JavaScript would have no issues interpreting the code then I suppose that's a reasonable reason for doing so.
# Posted By Bob Silverberg | 5/19/10 12:57 PM
you don't need the "!= 0", you can just check against the length as it will return a boolean, not an object.
# Posted By kevin | 10/15/11 9:47 AM