Javascript add item to current array
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 = [];
.
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");