Extracting information from ul li div elements and saving it in JSON format

I have been pondering this issue for the past few hours and haven't been able to find a solution. Essentially, I have a list structured like this

<ul class="list"> 
     <li class="user">
         <div class="name">Name</div>
         <div class="surname">Surname</div>
     </li>
     <li class="user odd">
         <div class="name">Name</div>
         <div class="surname">Surname</div>
     </li>
     <li class="user">
         <div class="name">Name</div>
         <div class="surname">Surname</div>
     </li>
     <!--And so on....-->
</ul>

Here is how my nightwatch script is set up

.elements('css selector','.li',function(result){
    console.log(result.value);
  });

The result is an empty array []

My main question is what would be the most effective way to extract all the data in ul li div tags and output it as a JSON object using console.log?

Similar to:

{
    "name": "name",
    "surname": "Yaya",
}, 
{
    "name": "name2",
    "surname": "Yaya2",
}, 

If anyone can offer assistance or guidance on how to achieve this, I would greatly appreciate it.

Answer №1

One possible approach in pure JavaScript could be to iterate over a list of elements and extract specific data from them.

var items = document.querySelectorAll("ul li"),
      index = 0,
  jsonData = [];
for (var item of items) {
  var divs = item.getElementsByTagName("div"),
     itemObject = {};
  for (var div of divs) itemObject[div.className] = div.textContent;
  jsonData.push(itemObject);
}
jsonData = JSON.stringify(jsonData);
console.log(jsonData);
  <ul class="list">
    <li class="user">
      <div class="name">Name</div>
      <div class="surname">Surname</div>
    </li>
    <li class="user odd">
      <div class="name">Name</div>
      <div class="surname">Surname</div>
    </li>
    <li class="user">
      <div class="name">Name</div>
      <div class="surname">Surname</div>
    </li>
  </ul>

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

A step-by-step guide to displaying image upload previews using React

I am currently working on developing an image upload form with the use of Next.js/React.js. The goal is to allow users to assign tags to each uploaded image and display a preview of the image using 'URL.createObjectURL'. Although the uploading pr ...

Surprising outcome encountered while trying to insert an item into a list

I'm a bit puzzled by the current situation where: let groupdetails = { groupName: "", }; const groupsArray = []; groupdetails.groupName = 'A' groupsArray.push(groupdetails) groupdetails.groupName = 'B' groupsAr ...

Combining Arrays in MATLAB by Matching Specific Columns

After obtaining a NetCDF file containing variables such as day (in julian), latitude, longitude, and ozone, I successfully converted the file into a 3D matrix ordered by longitude, latitude, and day. In addition, I possess a .mat file that includes Year, ...

Guide on merging arrays and displaying them in a single table

After decoding three JSON arrays into PHP associative arrays, I am faced with the result shown in the following image: My next goal is to display these three arrays in a single table similar to the one depicted below: If you have any insights or suggesti ...

What could be causing this hydration error in NextJS in the development server build but not in the production build?

By using the create-next-app command and implementing this code snippet, a hydration error occurs on the client side when running the next dev server. The code in pages/index.js: export async function getServerSideProps(context) { const x = Math.random( ...

React Native Function fails to return a value

Within my React Native app, there's a page called RepsPage that displays a scroll view using an array of IDs. I'm passing this array to a function named renderRep, attempting to create a view for each item in the array. However, the return statem ...

Generating .npy data with Numpy to use as input for a Convolutional Neural Network

I am a beginner in Python and working with a .npy file as input for my CNN model. Many tutorials I have found use Keras, but unfortunately I am not permitted to use it. Therefore, I need to know how to read just one array from my .npy file. The file contai ...

toggle back and forth between two div elements

I am trying to create a toggle effect between two divs, where clicking on one will change its border and header color to red while the other div disappears. I have tried using an IF statement in my JavaScript code, but it is not working as expected. Can so ...

Converting a JavaScript variable into an xls or csv file

My application currently uses Javascript for calculations and data plotting, but I want to give users the ability to download the data as a csv or xls file. Is there a way in Javascript or another method where users can click a button, enter a filename, an ...

Save a collection of controller instances within a separate controller in AngularJS

I am in need of an angular example where one controller wraps another. For instance, I am looking to divide some logic between EndpointListController and EndpointController. EndpointListController will handle retrieving data from storage, along with funct ...

Is the RadioButton change jQuery function malfunctioning following modifications to the DOM?

After updating the HTML of the radio button (with the same name) through AJAX based on certain logic (such as rate or duration changes), I noticed that the change(function(e) method worked perfectly before the DOM was updated. However, once the DOM chang ...

Pull JSON data from an Ajax application and cycle through the JSON values in a separate function

As I delve into the world of Ajax, I find myself grappling with a particular issue - the feasibility. My current endeavor involves fetching data from a db.json file using Ajax. { "transactions": [ { "date": "4/3/2021", "description": "Electric bill", ...

Enhance a JSON array with Ruby

I have come across this json snippet: { "kind": "something", "rules": [ { "rule1": [ "something1", "something2", "something3" ], "rule2": "something" } ] } In order to include "something4" in rule1, ...

Tips for preventing click events from interfering with execution in React

On my screen, there is a specific image I am looking to prevent all actions while a process is running. When I trigger the Execute button, it initiates an API call that can take 4-5 minutes to complete. During this time, I need to restrict user interacti ...

How to fetch a list of users in an organization from Azure DevOps using Python API call

I'm attempting to create a basic api call in Python to Azure DevOps to retrieve a list of users. The URL is returning results when accessed through a browser, but I am encountering an error while scripting it as shown below. I need assistance in prope ...

The Angular project seems to be experiencing technical difficulties following a recent update and is

Recently, I made the transition from Angular 6 to 8 and encountered two warnings during the project build process that I can't seem to resolve. Despite searching online for solutions, nothing has worked so far. Any help would be greatly appreciated. ...

What is the best way to fix the lint check error within a Vue file's styling?

Is there a way to eliminate the red wavy lines on the screen? ...

Error occurred while trying to fetch the Backbone.js collection due to undefined value of 'this._byId'

I am currently working with coffeescript and my code is quite straightforward: class SomeCollection extends Backbone.Collection constructor: (@options) -> url: -> "#{$SCRIPT_ROOT}/some/data/#{@options.someId}" model: SomeModel class SomeV ...

Is it possible to run concurrent PostgreSQL queries in NodeJS?

I'm unsure why, but the task is supposed to be run in parallel and should only take 2 seconds: const test = async () => { client.query("SELECT pg_sleep(2) FROM test", (err, result) => { console.log("DONE!"); }) client.query("SELECT pg ...

Tips for expanding AntD Table to show nested dataSource values

I need help dynamically rendering data into an antD expandable table. The data I have is a nested object with different properties - const values = [ [name = 'Josh', city = 'Sydney', pincode='10000'], [name = 'Mat ...