Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript add item to current array

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 ?

like image 783
Vinay Avatar asked Mar 08 '11 03:03

Vinay


People also ask

How do you add value to an existing array?

To add new value to an existing array, use the JavaScript splice() method.

Can you add object to an array in JavaScript?

There are 3 popular methods which can be used to insert or add an object to an array. The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method.

How do you add an element to the end of an array in Java?

In Java, arrays can't grow once they have been created; so, to add an element, you need to: Create a new, larger array. Copy over the content of the original array. Insert the new element at the end.

How do you push an element to an array at first position?

Adding new elements at the beginning of the existing array can be done by using the Array unshift() method.


2 Answers

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 = [];.

like image 184
Matt Ball Avatar answered Oct 11 '22 22:10

Matt Ball


If you want to push all <a> elements to the array, you have to convert the NodeList to an array first. Most people use Array.prototype.slice.call(nodelist).

Once you have an array, you can then use array.push in conjunction with function.apply to push them in one call.

The resulting code looks like:

var arrayValues = [];
arrayValues.push("Value 1");
arrayValues.push("Value 2");
arrayValues.push.apply(arrayValues, Array.prototype.slice.call(document.getElementsByTagName('a')));
arrayValues.push("Value 3");
like image 42
Thai Avatar answered Oct 11 '22 22:10

Thai