JavaScript sugar of the day

So I needed to use the slice function in the result of a getElementsByClassName() call.  Something like:

var elements = document.getElementsByClassName(‘MyClassName’);

var copyOfElements = elements.slice(0);

However this fails on the second line because slice is not a function on the elements objects.  The elements object is of type HTMLCollection, even though HTMLCollection appears very much like an array it isn’t exactly one, however there is a solution to be able to use slice with my object.

It comes in the form of using the call method on the Function Type.  JavaScript unlike other languages allows you to get a handle on a Function just like its any other type.  So for instance if I return ‘MyString’.indexOf it literally gives me the Function Object.  Now once you understand that, you can see that maybe the Function Object has methods of its own.  One of these methods is ‘call’  what call allows you to do is basically inject your own object for the ‘this’ of a Function.  In my example I can use the call method to use Array’s slice method on an object of another type, very easily.  Like so:

var elements = document.getElementsByClassName(‘MyClassName’);

var copyOfElements = [].slice.call(elements, 0);

However be careful of doing this as obviously not all objects are equal and therefore could cause you issues down the road if the structures and methods don’t line up.

Advertisements

One thought on “JavaScript sugar of the day

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s