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

Exploring the Depths of Multidimensional JSON Arrays in PHP

I am currently working on developing a web-based file manager that allows me to organize, view, create, edit, and delete folders and files. In order to store information about these folders, files, and subfolders, I am in need of an appropriate data struct ...

At what point are DOMs erased from memory?

Recently, I've been working on an application that involves continuous creation and removal of DOM elements. One thing I noticed is that the process memory for the browser tab keeps increasing even though the javascript heap memory remains steady. To ...

The art of positioning images and creatively cropping

Seeking advice on allowing users to dynamically position and clip an image on a webpage. I've tried using CSS and JavaScript for clipping and resizing, but it's not working as expected. If PHP could provide a solution, that would be ideal for my ...

What could be the reason behind TypeScript ignoring a variable's data type?

After declaring a typed variable to hold data fetched from a service, I encountered an issue where the returned data did not match the specified type of the variable. Surprisingly, the variable still accepted the mismatched data. My code snippet is as fol ...

ESLint warning: Potentially risky assignment of an undetermined data type and hazardous invocation of an undetermined data type value

Review this test code: import { isHtmlLinkDescriptor } from '@remix-run/react/links' import invariant from 'tiny-invariant' import { links } from '~/root' it('should return a rel=stylesheet', () => { const resp ...

Searching for a specific element in jQuery by querying a string

I have a situation where an ajax request is made to send text using the POST method to another PHP page. This PHP page then converts the text into markdown format and sends it back. Here's an example of what it looks like: "<p>Meep, meep, <e ...

Choose Status Menu DiscordJS version 14

Is there a way to get help with changing the bot's status if it's not working properly? The value of the variable "statuses" is set as status, but the status itself does not change. Using client.user.setStatus('dnd'); can sometimes work ...

Nightwatch refusing to close even after executing browser.end()

Upon running Nightwatch, I am faced with an issue where the nightwatch process continues to run even after the tests have successfully completed and the browser windows have closed. The message "OK. 10 total assertions passed" is displayed, but the process ...

Challenges related to using the require() method in JavaScript

I've been encountering an issue while trying to run the JavaScript client for the Tumblr API from their Github repository. The error message I keep getting is "require not defined" which has led me on a hunt across various forums and websites, includi ...

Issue detected: Click event for Backbone not properly registered

Hey there, I'm new to Backbone.js and having some trouble with a login feature. Despite initiating the view, I can't seem to get the click event to fire during an ajax call for logging in. Any ideas on what I might be doing wrong? I've even ...

Toggle the visibility of HTML elements by utilizing a JavaScript checkbox event

I have put together these JavaScript functions to hide the delivery address fields on my shopping cart address form if the goods are being sent to the billing address. The functions control the visibility of the HTML wrapped by... function getItem(id) { ...

The JavaScript program is occasionally receiving unconventional input

I'm really struggling with this one. As part of a programming exercise, I am developing a JavaScript calculator. You can access the functioning calculator here on Codepen. At the bottom left corner of the calculator interface, you will notice a "+-" ...

The condition is not established by the Firestore where clause

I'm working on a function that includes two where clauses. My objective is to verify the existence of a document based on the presence of two specific IDs. However, when I execute the function, it retrieves all the records in the collection instead. C ...

Invoke the REST API and save the compressed file onto the local machine

This is the code snippet I currently have: jQuery.ajax({ type: "GET", url: "http://localhost:8081/myservicethatcontainsazipfile", contentType:'application/zip', success: function (response) { console.log("Successful ...

What is the best way to locate a function (whether it be a GET, POST, etc.) within index.js using an Express router

I've been trying to set up a router in Express, following a tutorial. However, my code can't seem to find the function get/users. Interestingly, it works fine when I include it in index.js index.js : const express = require('express' ...

The Facebook SDK's function appears to be triggering twice

I am currently in the process of integrating a Facebook login button into my website and have made progress, but I have encountered a problem. The Facebook SDK JavaScript code that I am using is as follows: function statusChangeCallback(response) { ...

Troubleshooting: Issue with append function not functioning properly after click event in Angular

I am struggling to implement a basic tooltip in AngularJS. Below is the HTML I have: <span class="afterme" ng-mouseover="showToolTip('this is something', $event)" ng-mouseleave="hideToolTip();"> <i class="glyphicon glyphicon-exclama ...

Axios is experiencing challenges in transmitting the cookie

Even after attempting to include {withCredentials: true}, I am still facing issues with sending the cookie to the backend server. return await axios.post(`${API_URL}/posts/category/${id}`, { withCredentials: true }) https://i.stack.imgur.com/Cr8xv.png ...

Is using JQuery recommended for implementing onclick and onchange events?

Hello there, I'm completely new to the world of jQuery and currently facing a bit of confusion. Here's my dilemma: should I be utilizing jQuery with the onclick event or the onchange event for an element using something like this: $(selector).som ...

No data received from AJAX response

I've spent around 8 hours trying to figure this out with no success. Using $.ajax, I am trying to retrieve data from my database through a PHP script. However, it seems like it's not working in this particular case and I have no idea why. The va ...