Jquery: why does the selector return an array to me, but doesnt attribute?

I am trying to better understand JQ. I am calling a JQ object

$(".FamiliesList li li span[class!='']").prev().find('option:selected') 

this returns me an array of all parameters for which the parent of its class has a class name.

 [option, option] 

Now I want to return an array of parameter values

 $(".FamiliesList li li span[class!='']").prev().find('option:selected').attr('value') 

this returns me only the first child value and the full array of values.

Why?

I would appreciate help and understanding jq better :)

Thanks.

+4
source share
5 answers

The best answer I can offer is how the API works. I agree with you that things like attr and val will be more consistent if they return arrays (at least if the selector matches multiple elements).

You can get this effect with $.map if you want:

 var attrs = $.map($('div.something'), function(element) { return $(element).attr('whatever'); }); 

Now "attrs" will be an array. You can also write your own function.

In any case, it’s important to note that arrays exist and then there are “jQuery objects”. This will never make sense for the "attr" or "val" (or something like that) that will be used in the middle of the jQuery set of operations if you think about it.

+9
source

Actually, $ (selector) does not return an array. The result of $ (selector) is a jQuery object, which is defined as a "set of matched elements." This set may contain 0, one or more "elements", but jQuery itself remains the only object. Just a box that can't hold anything.

So, if $ (...) does not return an array, what could be the reason for attr () or val () to return it? That's why the getters property always (?) Returns the properties of the first element in the jQuery object to which they apply.

+3
source

try

 $(".FamiliesList li li span[class!='']").prev().find('option:selected').each(function () { return $(this).attr('value'); });` 
+1
source

You can do this using .map() , for example:

 var values = $(".FamiliesList li li span[class!='']").prev() .find('option:selected').map(function(function() { return $(this).attr('value'); }).get(); 

This will get [value1, value2, value3] , an array of values ​​of the selected parameters.

+1
source

Wouldn't you be looking for something like

 $(".FamiliesList li li span[class!='']").prev().find('option:selected').each(function() { return this.attr('value'); }); 

Afaik, the attr () method does not work on multiple objects, so you will need to call each () on the returned objects.

0
source

Source: https://habr.com/ru/post/1307035/


All Articles