June 14

Node list is not array

Date: June 14, 2009. Comments»

Node list is a collection of DOM Nodes. Most of them who code in Firebug tend to consider the node list as array because it looks like any other array. Node list has just two properties length and index. If you want to iterate on that you can use the old school way of incrementing the index or do any of the Enumerable functions by passing node list to call method. Let me show how to do that.

Example:
>>> foo = $$('div.post')
[div.post, div.post, div.post, div.post, div.post]
>>> Array.prototype.splice.call(foo)
>>> foo.each(function(item){console.log(item)})
<div class="post">
<div class="post">
<div class="post">
<div class="post">
<div class="post">
[div.post, div.post, div.post, div.post, div.post]

So what does call do? Call allows you to invoke a function as if it were a method of some other object. On above example foo is a node list its not a array but still I could able to splice that. ECMAScript specifies two methods call and apply. Both does relatively same job except the type of the argument. Apply takes a array as a argument.

Comments

sam - August 05, 2009.
Thank you very much for this useful information. Please keep on . I am looking forward to read your next great article.3d Animation Best regards!!! Sam
Thomas - August 05, 2009.
I agree with what you have to say.....web design London
Leave Comment: