Convert Array Like Object to an Array


/ Published in: JavaScript
Save to your folder(s)

Some HTMLCollection objects such as returned from document.getElementsByTagName() look like arrays but are not. You will need to run the object through slice.call() to convert to an actual array.

This function will convert array like objects into a real array. IE does not support slice.call(). The try-catch will genereate an exception and convert object to an array with a loop for IE.


Copy this code and paste it in your HTML
  1. function makeArray(items)
  2. {
  3. try {
  4. //this converts object into an array in non-ie browsers
  5. return Array.prototype.slice.call(items);
  6. }
  7. catch (ex) {
  8. var i = 0,
  9. len = items.length,
  10. result = Array(len);
  11.  
  12. while(i < len) {
  13. result[i] = items[i];
  14. i++;
  15. }
  16.  
  17. return result;
  18.  
  19. }
  20. }
  21.  
  22. var inputs = document.getElementsByTagName('input');
  23.  
  24. var inp = makeArray(inputs);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.