Tuesday, October 9, 2012

Array returned from jQuery selector and html element

When using jquery id selector, it will only return a single object. However, similar to other jquery selector, the returned object is wrapped in a jquery object array. Note all jquery selector methods return an array, as it is always possible to match more than one elements for the selector.
If you call a jquey method to retrieve the attribute on the returned array, like val(), it actually returns the attribute of the first element. When the object is selected by id, it is perfectly fine, as there is only one element. However, if the array contains multiple elements, it does not have much sense to just return the first element's value when calling the method on the array. Although, in both cases, setting the value is fine, as it makes sense to set the same value for all elements or a single element.
In order to return a particular jquery element from a multiple element array, call jQuery('selector:eq(index)') method. Remember, the returned value from the method is still wrapped in a jquery array, the only difference is the array will only contain a single jquery object.
In order to return a particular htmlElement, call jQuery('selector').get(index). The returned object is a single html object, (not a array, not a jquery object), and it has all the applicable attribute defined for html element such as value attribute.



No comments:

Post a Comment