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:

if ($("#fieldA").length != 0) {
    $("#fieldB").attr("disabled", "disabled");
}

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

jQuery.fn.exists = function() { return (this.length > 0); };

Which would allow me to change the above code to:

if ($("#fieldA").exists()) {
    $("#fieldB").attr("disabled", "disabled");
}

Nice, innit?

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

Azadi
# Posted By Azadi Saryev | 5/19/10 3:57 AM
Dan G. Switzer, II's Gravatar 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
Bob Silverberg's Gravatar @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