> > I've been hacking with jQuery on and off lately and I've
> > now hit the annoying problem of not being able to access
> > simple DOM 0 properties unless, apparently, using either
> > of the following syntaxes:
> >
> > $('#foo')[0]
> Will throw error if there is no match, IIRC.
No, it won't. It is not an error to fetch a nonexistent array element. It
returns undefined.
You could even do $('#foo')[12345] and it wouldn't throw an error.
Of course, if there is no element with id 'foo', this will throw an error:
$('#foo')[0].whatever
Because $('#foo')[0] returned undefined, so you are trying to access the
'whatever' property of... undefined.
It's just as if you had done:
var array = [];
var element = array[0]; // not an error
var element1 = array[1]; // also not an error
// element and element1 have a value of undefined, so...
alert( element ); // alerts "undefined"
alert( element.test ); // throws an error
But you can do this:
var element = $('#foo')[0];
if( element ) {
// now you know that element exists
// and can access its properties
}
> Use $('#foo:nth(0)') instead. For just first match, you could use $
> ('#foo:first')
That will still return an array (if it works), leaving you in the same boat
as before.
-Mike