Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split jQuery collection into an array of individual jQuery objects

I am wondering if there is a way to split a jQuery selector which contains a collection of elements into an array of selectors, one for each element. For example, I have:

fields = row.find('input');

which returns a selector containing multiple input elements. I know I can use

fields.eq(index).val()

to access individual values, but is there an easy way to construct or convert fields to an array of selectors so I can just use

fields[index].val()

Edit:

Yes I realize you can use .toArray(), but as has been pointed out below, that returns an array of DOM elements. Then you'd have to loop through to convert these to selectors - too much extra work.

like image 833
Jhacker Avatar asked Mar 16 '23 13:03

Jhacker


1 Answers

How about a small plugin to do this for you?

$.fn.toJqArray = function(){
   var arr = [];
    $(this).each(function(){
       arr.push($(this)); 
    });
    return arr;
};

var inputs = $('input').toJqArray();
var value = inputs[0].val();

Here's a fiddle with usage.

like image 73
Dave Salomon Avatar answered Apr 25 '23 11:04

Dave Salomon