Question

I am curious about the reasoning behind some of jQuery API architecture choices.

FROM THE DOCUMENTATION

attr():

Get the value of an attribute for the first element in the set of matched elements.

val():

Get the current value of the first element in the set of matched elements.

Even if I have many objects:

$('div').val()

would only return the value of the first element.

But SETTING works differently:

val(value):

Set the value of each element in the set of matched elements.

attr(attributeName, value):

Set one or more attributes for the set of matched elements.

So my questions:

  • Why decide that getter operations like val() should return only the first value instead of an array of values? (The user has to use a map operation if he wanted all of them in an array)

  • Why not do the same with setter operations like .val(value)?

  • I can see a use case (with $('div').first()) where we expect the call to val() to return the value (we know there is only one dom element in the matched set) instead of an array of length 1. But why not handle it with a concept of a "single dom element query object" (that only gets created after calls to methods like first() or eq())?

Was it helpful?

Solution

Caveat: I do not take part in the jquery development, so these thoughts may be entirely off the actual design decisions.

Anyway, imho your proposal does not seem to offer any advantage:

  1. to process an array of data gleaned from the elements of a jquery collection the user would have to iterate over this array anyway - this can be done using jquery's each method in the first place which has the additional benefit of immediate access to the element carrying the attribute:

    $("my_spiffy_selector").each( function ( idx, e ) { $(e).attr("blarf").whatever(); });

  2. Otoh it would complicate matters (at least the jquery code base), if the getters return type would be polymorphic or if there were different getters.

  3. The arguably most common use case would entail at least an additional .first() call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top