javascript - Why DOM wrapper methods use the first element and the whole element list inconsistently?

StackOverflow https://stackoverflow.com/questions/13294834

Вопрос

Libraries I've seen have DOM wrappers that inclusively handle only the first element of the list in some case, like:

return this[0].innerHTML

and use the whole list in some other like:

for( var i=0, l=this.length; ++i<l; ) this[i].className = cls;
return this

Why is this approach accepted?

I think singling out the first element defeats the purpose of having methods that apply the same thing on the rest of the list. Isn't it bad to have dubious functions? I know it suits many people..but it feels inconsistent and I'm interested in why this is accepted so widely.

EDIT as an example:

jQuery.html()

If the selector expression matches more than one element, only the first match will have its HTML content returned.

why not all?

the hide() method in bonzo, from Dustin Diaz

//...
hide: function () {
  return this.each(function (el) {
     el.style.display = 'none'
  })
}

why not only the first?

Это было полезно?

Решение

The accessor methods in jQuery return single values because it's simpler and more generally useful. If the .html() API were to return the value if innerHTML for all elements, that'd mean it'd have to return an array. That, in turn, would mean that in the most common case of wanting the contents of a single element, you'd have to add the array access. There's also the problem of knowing exactly which returned value goes with which selected element. In other words, if .html() returned an array of element contents:

var contentList = $('.someClass, span, .hidden .container').html();

If "contentList" were just a simple array, what use would it be? How would the code know for each element which DOM node it came from? Of course there are solutions to this, but again the simple case is made complicated in order to support a rare general case.

It's possible of course to get the list yourself with .map(). I think this is just an issue of smart, practical, pragmatic API design.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top