jQuery ID Selector ("#id") Returns Array
Solution 1:
$j("#divID").val()
will work just fine.
Per the jQuery documentation, .val()
will return the value of the first element in the set of matched elements.
It's worthwhile understanding conceptually how jQuery works in order to see why it works this way. The result of any selector query is a jQuery object. It's that jQuery object that contains the myriad of methods that jQuery offers. .val()
is one of those methods as are things like .fadeIn()
, .hide()
, etc... Those methods are not methods on a DOM object, but methods of a jQuery object. Because jQuery objects are general purpose and can hold 0, 1 or more DOM objects in their internal array, you get the same jQuery object back from a jQuery selector call whether the results have 0, 1 or more DOM objects in it.
Thus $j("#divID")
that contains only one object returns the same type of object as $j(".rows")
which might contain hundreds of DOM objects. This vastly simplifies jQuery programming because you don't have to do things differently depending upon how many objects come back from the selector query.
When you refer to $j("divID")[0]
, you are reaching into the jQuery object's internal array of DOM objects (that was populated on the selector query) and fetching the first DOM object in that array. At that point, you have a normal DOM object, not a jQuery object and you can use normal DOM methods or attributes on it. Occasionally this is required (to fetch the actual DOM object), but usually, it's easier to just use the methods that jQuery provides on the jQuery object. There are lots of advantages to using them such as you can chain multiple requests to most methods and it will iterate over all the DOM objects in it's internal array for you automatically.
For example, you you called this: $j("rows-even").hide()
and there were 20 rows with that class, then all of them would each be operated on by the hide() method with no more code than this. Of you could chain multiple methods together like this: $j("rows-even").slideUp().slideDown()
. In this case, you're running an animation and jQuery will chain these two animations together, automatically starting the second one when the first one finishes. It's all pretty useful in many circumstances and can save a ton of code over what would normally have to be written using plain JS.
Solution 2:
$j("#divID")
returns a jQuery
object. In order to get the value of the selected element you have to call its val
method to get the value.
Use $j("#divID").val();