Save the list of arrays into a designated variable

I am struggling to save the array list in a variable and I'm not sure how to go about solving this issue.

The xpath query successfully retrieves a list of items, which are being displayed in the console without any problems. However, I am unable to figure out a way to store this list in a variable for later use.

When I attempt to assign the values to an "arrayList" variable, only the last item from the array is returned despite seeing all items in the console output.

Does anyone have any suggestions on how to tackle this problem?

var iterator = document.evaluate('xpathgoeshere', document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);

try {
  var thisNode = iterator.iterateNext();

  while (thisNode) {
    var arrayList = (thisNode.textContent);
    var thisNode = iterator.iterateNext();
    for (var i = 0; i < arrayList.length; i++) {
      console.log(arrayList);
    }
  }
} catch (e) {
  dump('Error: Document tree modified during iteration ' + e);
}

Answer №1

Initially, remember to update thisNode after finishing your loop because the arrayList relies on thisNode.

Another issue could be that you are assigning iterator.iterateNext(); to a new variable thisNode within the while-loop instead of updating the existing variable thisNode inside the try-block (due to the use of var before it).

Give this a shot: :)

var iterator = document.evaluate('yourxpathhere', document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);

try {
  var thisNode = iterator.iterateNext();

  while (thisNode) {
    var arrayList = thisNode.textContent;

    for (var i = 0; i < arrayList.length; i++) {
      console.log(arrayList[i]);
    }    
    thisNode = iterator.iterateNext();
  }
} catch (e) {
  dump('Error: Document tree modified during iteration ' + e);
}

As pointed out by Steven, thisNode.textContent is a string. Depending on the format of your string, you might need to split() it first or use JSON.parse() if it's a JSONstring in order to extract your Array.


However, if the items of your Array should be the content of thisNode.textContext, consider this alternative approach:

var iterator = document.evaluate('yourxpathhere', document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);

try {
  var thisNode = iterator.iterateNext();
  var arrayList = [];

  while (thisNode) {
    arrayList.push(thisNode.textContent); 
    thisNode = iterator.iterateNext();
  }

  console.log(arrayList);

  for (var i = 0; i < arrayList.length; i++) {
    console.log(arrayList[i]);
  }   
} catch (e) {
  dump('Error: Document tree modified during iteration ' + e);
}

Answer №2

Store all nodes in an array.

var elementIterator = document.evaluate('//div', document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);

const elementsArray = []

try {
  var currentNode = elementIterator.iterateNext();
  while (currentNode) {
    elementsArray.push(currentNode)
    var currentNode = elementIterator.iterateNext();
  }
} catch (error) {
  console.log('Error: Document structure has been modified during iteration ' + error);
}

console.log(elementsArray);
<div>
  <div>Element 1</div>
  <div>Element 2</div>
</div>

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

What is the best way to divide a string into separate sections?

I have a string containing multiple words separated by spaces, like "firstword second third", and an ArrayList. My goal is to split the string into individual pieces and then add these 'pieces' as strings to the ArrayList. For instance, if we ta ...

Converting a three.js scene into SVG or alternative vector format for export

Can an SVG- or other vector-formatted image be exported from a scene rendered using three.js's WebGLRenderer? What about from a scene derived from CanvasRenderer? If not, how can one set up SVGRenderer with three.js? Creating a new THREE.SVGRenderer( ...

Discover the combobox element and its value can be easily achieved by using Selenium's find_element_by_xpath method

I am having trouble setting a value in a combobox using selenium. The find_element_by_xpath statement is failing to locate the combobox by class or ng-model. Specifically, I am attempting to change the time period for a stock from one day to one week. Her ...

Guide to changing the border color in a Material-UI TextField component styled with an outline design

To complete the task, utilize the Material UI outlined input field (TextField component from "@material-ui/core": "^4.12.2",) and apply a custom blue color style to it. Here is the outcome of my work: https://i.sstatic.net/lw1vC.png C ...

Adding images to your SVG using Bobril is a simple process that can add visual

I have been attempting to insert an image into an SVG using Bobril, but the following code is not functioning as expected: { tag: 'svg', children: { tag: 'image', attrs: { 'xlink:href': &ap ...

What makes the middle element in a sorted array the majority element?

While working on this particular problem on Leetcode, I came across a solution that left me puzzled. The solution suggested to "sort the array and the middle element will be the majority." My question is: "Why is the middle element of a sorted array c ...

Show a specific form field based on the chosen option in a dropdown menu using Angular and TypeScript

I am looking to dynamically display a form field based on the selected value from a dropdown list. For instance, if 'first' is chosen in the dropdown list, I want the form to remain unchanged. However, if 'two' is selected in the drop ...

Steps for generating an HTML form in a fresh window

I am currently working with this function: // open a new window. Create and submit form function createSubmitForm(response) { var external = window.open('about:blank', 'external'); var doc = external.document; var body = $( ...

Storing data for extended periods in NodeJS

Currently, I have a node server up and running. To maintain its uptime when I'm not actively developing, I utilize npm forever. However, for editing purposes (such as restarting the app upon edits or uploads), I rely on npm nodemon. After restarting ...

Error: JSON parsing error encountered due to an unexpected token 'U' while trying to read a file with

Currently, I am utilizing Node.js version 12.14.1 and encountering a problem while attempting to parse a JSON file that includes the \U0001f970 character. The file's content that needs to be read and parsed is as follows: {"randomKey": ...

What varieties of ajax styles are there?

Although I am still relatively new to utilizing ajax, I have found a lot of success in my endeavors so far. The majority of my ajax calls tend to follow this format: function saveQueryProf(){ var currentDate = new Date(); var date=currentDate. ...

The error "converting circular structure to json" occurred when trying to create a JSON web token, resulting in an unhandled TypeError

screenshot of error I recently encountered an issue while implementing JSON web token authentication on my application. The error message displayed was: " Unhandled rejection TypeError: converting circular structure to JSON " Upon further investigation, ...

Is there a way to delegate the operation of Object3d.toJSON() to a web worker for optimization?

Is there a way to efficiently convert the active scene in threejs to a JSON object? The process seems to slow down as the models get larger, making it difficult to show a progress bar. I attempted sending the threejs scene to a web worker for conversion, ...

Chrome and Firefox experiencing intervals set issues

Having trouble with my websites, particularly with the sliders in Chrome. I'm not a JS expert but any assistance would be greatly appreciated. The affected sites are and . It seems like the issue lies within this snippet of code: if ($("#mainSlide") ...

Verifying the accessibility of a website using JQuery/Javascript

I am attempting to use JavaScript to ping a website and display the result. Unfortunately, I have not had any success with this JSFiddle: https://jsfiddle.net/yyjowtru/ Although I believe I am close to achieving the desired outcome, changing the URL in t ...

Error encountered with jQuery XML: 'Access-Control-Allow-Origin' header is not present on the requested resource

For a personal project I'm working on just for fun, I'm trying to read an XML file from , parse the data, and use it to convert currency values. Although my code to read the XML is quite basic, I encountered the following error: XMLHttpRequest ...

What is the best way to display my to-do list items within a React component

I'm working on a straightforward todo application using fastapi and react. How can I display my todos? I attempted to use {todo.data}, but it's not functioning as expected. Here is my Todos.js component: import React, { useEffect, useState } fro ...

Is it possible to combine EJS compilation and html-loader in the html-webpack-plugin?

I need the html-webpack-plugin to generate my html using my .ejs template that contains <img> tags. The html-loader can update the image URLs in my <img> tags created by Webpack, so I am including it in my configuration: test: /& ...

What is the best way to ensure the flat list only renders once?

My objective is to display the ComponentTwo Flatlist just once, however, I am currently seeing the output as shown in image1, whereas I want it to be displayed like in image2. To showcase this issue, I have included a snack link containing the relevant cod ...

What is the best way to delete a property from an object in an array?

I have a Vue component with an array that includes IDs which I want to remove while keeping the other elements intact. Is there a way to achieve this within a method? Is it possible to filter out the ID index from the array using Vue methods? var vm = ...