> From: pd
> 
> 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]
> 
> $('#foo').get(0)

pd, just to help clarify... The $() function returns an array of DOM
elements. You access elements of an array, of course, by using [n].

I don't know if I would call this an "annoying problem", it's just the way
it is.

Imagine this code:

   var myArray = [
      document.getElementById('foo'),
      document.getElementById('goo')
   ];

Now you have an array of two elements, [0] and [1], and each element is a
reference to a DOM element.

If you want the first element of the array, you would use:

   myArray[0]

And you could access DOM properties with:

   alert( myArray[0].id );  // alerts 'foo'

Or you could do:

   var firstElement = myArray[0];
   alert( firstElement.id );  // alerts 'foo'

What you couldn't do:

  alert( myArray.id );  // alerts undefined

After all, myArray is not a DOM element, it's an *array* of DOM elements.

A jQuery object returned by $() is no different. Whenever you see $(), think
"array of DOM elements".

(Well, it is slightly different - it is not an actual JavaScript Array
object, but it does have .length and [n] properties so it works like an
array for these purposes.)

-Mike

Reply via email to