0

I have come across the following code:

var userDetailsFields = $(formSelector + " input[type='text'], " + formSelector + " select").map(function(){
  return this.id;
});

I was wondering if the jQuery each would be more suitable to achieve the same result from a performance perspective..

AIM: return the value of each input and select inside a form.

Aessandro
  • 5,517
  • 21
  • 66
  • 139
  • 1
    How about `$(formSelector).find('input, select').each(function(){ //code });` - I'd say `each` is more readable when looping over jQuery objects. – gskema Jul 21 '15 at 12:02
  • would you say that from performance perspective is better? – Aessandro Jul 21 '15 at 12:02
  • 2
    You'll probably save more execution time if you write the selectors more efficiently – gskema Jul 21 '15 at 12:04
  • possible duplicate of [jQuery map vs. each](http://stackoverflow.com/questions/749084/jquery-map-vs-each) – raviolicode Jul 21 '15 at 12:05
  • a list/array of values (from the inputs and selects passed in) to update the same form... – Aessandro Jul 21 '15 at 12:09
  • I have put up a little example here: https://jsfiddle.net/mbrg701w/2/ i need to use the result which is "this.id" to update a form – Aessandro Jul 21 '15 at 12:11

1 Answers1

1
var userDetailsFields = $(formSelector).find("input[type='text'], select").map(function(){
  return this.id;
});

.each used to iterate over array-like and make something on each item. It's more generic function

.map - create new array base on source array-like object. It's more specific function

Speed will be the same, but semantic of task say that better to use .map

Vasiliy vvscode Vanchuk
  • 7,007
  • 2
  • 21
  • 44