Only a single element in the array is being pushed by the JavaScript code, not all elements

Having an issue with my script where it is only returning one element out of a class that has 10 elements. Can anyone help me pinpoint the problem?

`function() { var vins = document.querySelectorAll('.dws-vehicle-listing-item-field.dws-vehicle-field-vin');

for (var i = 0; i < vins.length; i++) {
    var array = [];
    var items = vins[i].innerText.replace(/ /g, "").split('\n')[2];
    array.push(items);
}
return array;

}`

Attempted to add exclusions in the code string to fix the issue, but still only getting one element returned. Any suggestions?

Answer №1

The main issue lies in the redeclaration of a new array instance within each iteration of the loop. To resolve this, it is advisable to initialize the array variable outside the loop;

let array = [];
for (let i = 0; i < vins.length; i++) {
    let items = vins[i].innerText.replace(/ /g, "").split('\n')[2];
    array.push(items);
}
return array;

Furthermore, I suggest avoiding the use of var and instead opt for const (for constant values) or let: further information available here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Parent controller was not in command before Child执行

When working with a parent view and a child view, I encounter an issue with accessing a json file. In the parent view, I retrieve the json file using the following code: $scope.services = Services.query(); factory('Services', function($reso ...

Using ng-repeat in conjunction with ui-router conditions

Utilizing ui router ($routeprovider and $locationprovider) for angular js, I am looking to adjust the array being looped through in an ng-repeat based on the current url/route. Despite browsing similar threads on stack, I have not found a precise solution ...

Setting up parameters and arguments in Vuex mutations: A guide

I am currently developing a todo list application using Vue.js, Vuex, and Firebase. The functionality of the app seems to be in working order with the Store file effectively managing the retrieval and display of entered todo items to and from Firestore. Ho ...

Error: Headers cannot be set once they have already been sent. I am perplexed as to why this is occurring

I can't seem to pinpoint the source of the problem...After researching the meaning of this error, it appears that I may be either sending a request or response twice somewhere in my code. However, I have thoroughly reviewed my code and cannot find any ...

Retrieving and storing information from a form without the need to submit it

I have been given the task of creating a load/save feature for a complex form. The goal is to allow users to save their progress and resume working on it at a later time. After much consideration, I have decided to implement server-side storage by saving ...

Utilizing class references within a method

I have been developing a script that is designed to dynamically load content into multiple predefined DIVs located in the topbar section of my website. Within the Topbar Object, there is an object called Ribbon which contains functions for manipulating on ...

The issue of 'position: fixed' not properly functioning within the Materialize CSS modal

My goal is to have the header of the Modal stay fixed while scrolling, but for some reason, the option position:fixed; is not working. I am currently using Materialize CSS to build the modal and surprisingly, position:sticky; is working. $(document).rea ...

Can you use an ajax post to search for a boolean in MongoDB without converting on the server side?

I am facing an issue with my mongo collection that has documents containing a boolean field: { name : "Tom", active : true } { name : "Jerry", active : false } In my application's client side, there is an element that triggers an AJAX po ...

Tips for clearing all content within a React Material UI table

How can I create a reset button to clear a table filled with user input data, without having to write functions from scratch? For example, similar to using clearLayer() for clearing a leaflet map. Thank you for any suggestions! //example of dynamical ...

Ways to resolve: The JSX component does not contain any construction or call signatures

I've been grappling with a persistent issue regarding the creation of custom elements dynamically in React TypeScript. If you're curious, you can check out the question here. const generalButtons: MenuButton[] = [ { text: "New Cl ...

Encountering a "Raphael is undefined" error message when working with Treant.js

I need help creating an organizational flow chart using treant.js. Below is my code snippet, but I'm encountering a 'Raphael is not defined' error that I can't seem to solve. Can someone please assist me with identifying the root cause ...

Initial React render fails to retrieve API data

I've encountered an issue during development where the page loads before the API data is sent. I attempted to use asynchronous functions, but it didn't resolve the problem as expected. I suspect that my approach may be incorrect. Here's a sn ...

What is the method for enlarging the width of the nvd3 chart timespan?

Click here In the Plnkr linked above, I have included the latest versions of d3 and nvd3 libraries. Upon initial viewing of the chart, you may notice that all the timespan ticks such as 09:00, 08:30, 08:00, etc., are overlapping on the left xAxis. The ti ...

Using an Ajax call within an event handler function

After spending a full day attempting to execute an AJAX call within an event handler function, I've tried various combinations of when(), then(), and done(), as well as setting async: false. However, I keep encountering undefined errors despite my eff ...

JSON data cannot be transmitted using AJAX

I created a function that tracks the time spent on a specific page and where the user came from. The data is collected and saved into a JSON object, but I encountered an issue when trying to send this JSON via ajax. Upon successful sending, I receive an em ...

When clicking on an item in the wishlist, only the text for that specific item should change,

Hi all, I'm in need of some assistance. I have successfully created a wishlist toggle where clicking on the heart icon changes it from an outline to solid. However, my issue lies in changing the tooltip text from "add to wish list" to "added to wish l ...

What are the steps to create a dynamic navigation bar in React without encountering hydration issues?

My goal is to dynamically show or hide links based on user authorization. Here's my initial approach: const Navbar = () => { const { canDo, ...} = useUser(); //A Zustand store return ( <> <div> <ul> ...

Error in Highcharts: The property '0' is undefined and cannot be read

Attempting to integrate data from a REST API into HighCharts, but encountering an issue: TypeError: Cannot read property 'series' of undefined. This function retrieves the data from the API: $scope.myData = function(chart) { HighCharts.query ...

Key in the calculation on Keypup for multiple rows, one row at a time

I want to create a calculation function for a form with multiple rows. The goal is to determine the totals for each row by multiplying the cost and unit price, then inputting the result in the total field. Below is the script that I attempted: <scrip ...

Gatsby's own domain and absolute links: the perfect pair

My goal is to establish a direct link to files (such as images and downloads) in my static directory. During development, the link should be http://localhost/myimage.jpg, and once deployed, it needs to switch to https://www.example.com/myimage.jpg. Is the ...