BMAC
BMAC

Reputation: 141

How does Array.prototype.slice.call work in this recreation of getElementsByClassName?

I have a piece of code that I mostly understand. The only piece that I don't understand is how the Array.prototype.slice.call works in this instance.

var getElementsByClassName = function(className){
  var elements = $('*').filter(function(index, node){
    // this will basically iterate through all nodes on the
    // DOM and check to see which node matches the className passed in.
    return $(node).hasClass(className);
  });
  // elements is an array of two elements. array[0] seems to be the non-enumerable
  // properties (but it has a length property?) and the other is the element on the dom. 
  // the usage below slices out array[0] and returns array[1], but since both
  // have a length property and numeric indices, why doesn't this usage return
  // both items?
  return Array.prototype.slice.call(elements);
};

I've left my comments/questions in-line. Any assistance would be greatly appreciated :).

Thanks, B

Upvotes: 1

Views: 211

Answers (1)

Pointy
Pointy

Reputation: 413720

Your code builds a jQuery object that contains only DOM nodes that have the searched-for class. The call to .slice() simply makes a copy of that. It would be somewhat simpler to just

return elements.get();

which would do the same thing. (And, of course, $("." + className) would replace the whole thing.)

jQuery objects are not arrays. They're made to mimic arrays, and the .slice() method isn't picky; so long as the object it's working on has a length method and numerically-indexed properties (which jQuery objects do), it's fine.

Upvotes: 1

Related Questions