Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: why a selector returns me an array, but attribute doesnt?

I'm trying to understand JQ better. I'm calling an JQ object

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

this returns back to me an array of all the options that their span parent's brother has a classname.

[option, option]

Now- I want to return back an array of the option's values

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

this returns back to me only the first child value, and a full array of the values.

Why?

I would appreciate to receive help and understand jq better :)

Thanks.

like image 925
neoswf Avatar asked Dec 10 '22 16:12

neoswf


2 Answers

The best answer I can offer is, "that's just the way the API works". I agree with you that things like "attr" and "val" would be more consistent if they returned arrays (at least in the case that a selector matches multiple elements).

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

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

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

In any case, it's important to note that there are arrays, and then there are "jQuery objects". It's never really going to make sense for "attr" or "val" (or anything like that) to be used in the middle of a set of jQuery operations, if you think about it.

like image 154
Pointy Avatar answered Jan 19 '23 07:01

Pointy


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 can contain 0, one or more "elements", but jQuery itself remains a single object. Just a box that can hold nothing or something.

So, if $(...) doesn't return an array, what would be reason for attr() or val() to return it? That's why property getters always (?) return the properties of the first element in the jQuery object they are applied to.

like image 40
user187291 Avatar answered Jan 19 '23 07:01

user187291