I’m selecting an array of input objects using jQuery and I’m running into an interesting problem when I try to chain together multiple methods after selecting one of the array elements. Can anyone explain to me why I get this behavior?
jQuery('.custom-size').first().find('input:hidden')
returns =>
[<input id="custom_order_custom_sizes_attributes_0_size_id" name="custom_order[custom_sizes_attributes][0][size_id]" type="hidden" value="138">
,
<input name="custom_order[custom_sizes_attributes][0][_destroy]" type="hidden" value="0">
]
If I select one of the elements using jQuery .first() or .last() and then call .val(), I get the expected value of "138".
When I try to use a location in the array, I can return the element of the array:
var input = jQuery('.custom-size').first().find('input:hidden')[1]
returns =>
<input name="custom_order[custom_sizes_attributes][0][_destroy]" type="hidden" value="0">
I can’t call .val() on this object however. Instead I get this error message:
TypeError: Object #<HTMLInputElement> has no method 'val'
I can use .slice(x,y) to return the single element, but this seems rather silly. What am I missing here.
The following code:
gets a single DOM element from the jQuery set. This code does the same as if you do
Retrieved DOM element doesn’t have
val()method, since it is not a jQuery object.In order to get the first jQuery object from jQuery set, you may use either
:eq()selector (or.eq()method), or:firstselector (or.first()method):