jQuery Quickie - Checking Whether an Element Exists
Posted At : May 18, 2010 3:47 PM | Posted By : Bob Silverberg
Related Categories: jQuery
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:
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:
Which would allow me to change the above code to:
2 $("#fieldB").attr("disabled", "disabled");
3}
Nice, innit?
if ($("#fieldA")[0]) {...}
Azadi
if( $("#fieldA").length ) doSomething();
A positive integer is evaluated as true in JS.
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.