Javascript add item to current array

Vinay picture Vinay · Mar 8, 2011 · Viewed 28.5k times · Source

I am trying to add an item to a current array.

var arrayValues = new Array();
arrayValues.push("Value 1");
arrayValues.push("Value 2");
arrayValues = document.getElementsByTagName('a');
arrayValues.push("Value 3");

By doing this way I get a error, and I dont get value 1 and value 2, after getting the hyperlink collection when I try to add a new item it throws Error: Object doesn't support this property or method which is the push method.

What is happening to the array after the collection of hyperlinks is assigned ? How can I add a new item to it ?

Answer

Matt Ball picture Matt Ball · Mar 8, 2011

Did you mean arrayValues.push(document.getElementsByTagName('a'));?

Otherwise, you're assigning the NodeList returned by getElementsByTagName(), which overwrites the array you had just pushed values into.

Side note: there's no reason to use new Array() here. Just write var arrayValues = [];.