Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript collection of DOM objects - why can't I reverse with Array.reverse()?

What could be the problem with reversing the array of DOM objects as in the following code:

var imagesArr = new Array();
imagesArr = document.getElementById("myDivHolderId").getElementsByTagName("img");
imagesArr.reverse();

In Firefox 3, when I call the reverse() method the script stops executing and shows the following error in the console of the Web Developer Toolbar:

imagesArr.reverse is not a function

The imagesArr variable can be iterated through with a for loop and elements like imagesArr[i] can be accessed, so why is it not seen as an array when calling the reverse() method?

like image 663
zappan Avatar asked Sep 05 '08 12:09

zappan


People also ask

Can I use array reverse?

reverse() The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.

What Reverse () will do in JavaScript?

The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.


1 Answers

Because getElementsByTag name actually returns a NodeList structure. It has similar array like indexing properties for syntactic convenience, but it is not an array. For example, the set of entries is actually constantly being dynamically updated - if you add a new img tag under myDivHolderId, it will automatically appear in imagesArr.

See http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-536297177 for more.

like image 63
Adam Wright Avatar answered Oct 07 '22 17:10

Adam Wright