Transform the HTML content into a JSON format file

I'm currently developing an online marketplace and trying to convert all product information like name, price, and description into json format. I have a sample code featuring a selection of products displayed in rows.

<div class='cakes'>
    <div class='col-3'>
        <img src = 'Images/banana cake.jpg'>
        <h4>Banana Cake</h4>
        <p>&#8373;30</p>
        <button class='add-to-cart' data-id='1'>Add To Cart</button>
    </div>
    <div class='col-3'>
        <img src = 'Images/pastry_box_1.jpg'>
        <h4>Pastry Box</h4>
        <p>Mini: &#8373;35 | Midi: &#8373;50 | Maxi: &#8373;90</p>
        <button class='add-to-cart' data-id='1'>Add To Cart</button>
    </div>
    <div class='col-3'>
        <img src = 'Images/cupcakes_12.jpg'>
        <h4>Cupcakes</h4>
        <p>Box of 4: &#8373;30 |  Box of 12: &#8373;85 | Box of 6: &#8373;40</p>
        <button class='add-to-cart' data-id='1'>Add To Cart</button>
    </div>

My goal is to compile each product's details into a .json file for my JavaScript implementation, but I'm uncertain on the required steps. The tutorial resources that I'm following include a .json file with the product info, however, the process of creating it has not been explained. Consequently, I'm struggling to proceed as intended.

Answer №1

It's quite surprising that the JSON responsible for creating the cart is missing.

But fear not, I have it right here!

const items = [...document.querySelectorAll(".cakes div")].map(div => {
  const name = div.querySelector("h4").textContent;
  const picture = div.querySelector("img").getAttribute("src");
  const description = div.querySelector("p").innerHTML;
  return {
    name,
    description,
    picture
  }
})

const cartJSON = JSON.stringify(items)
console.log(cartJSON)
<div class='cakes'>
  <div class='col-3'>
    <img src='Images/banana cake.jpg'>
    <h4>Banana Cake</h4>
    <p>&#8373;30</p>
    <button class='add-to-cart' data-id='1'>Add To Cart</button>
  </div>
  <div class='col-3'>
    <img src='Images/pastry_box_1.jpg'>
    <h4>Pastry Box</h4>
    <p>Mini: &#8373;35 | Midi: &#8373;50 | Maxi: &#8373;90</p>
    <button class='add-to-cart' data-id='1'>Add To Cart</button>
  </div>
  <div class='col-3'>
    <img src='Images/cupcakes_12.jpg'>
    <h4>Cupcakes</h4>
    <p>Box of 4: &#8373;30 | Box of 12: &#8373;85 | Box of 6: &#8373;40</p>
    <button class='add-to-cart' data-id='1'>Add To Cart</button>
  </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

Generating personalized MongoDB collections for individual users - A step-by-step guide

My query is more about the procedure rather than a specific coding issue. I am working on a node application and using DHTMLX calendar. What I aim for is to have each user with their own set of events on their individual calendar. Currently, the implement ...

How can the value be accessed when using getElementById in Angular for <mat-select> elements that do not have a value attribute?

Within a loop, I have an element that has a dynamically generated id: <mat-select multiple class="dw-input" [value]="element.txn_type_id ? element.txn_type_id.split(',') : []" id="field-{{element.Name}}-txn_type_id&quo ...

I'm working on separating the functionality to edit and delete entries on my CRM model, but I'm having trouble finding a way to connect these buttons with my data fields

I am encountering some difficulties while trying to implement separate functionality for editing and deleting items on my CRM model. I have already created the necessary API in Angular, but I am struggling to bind these buttons with my field. Any assistanc ...

Output certain values in a Python dataframe based on the lambda function applied

I am currently working on a piece of code that involves reading a json file and using a lambda function to remove certain values. Here is the code snippet: import pandas as pd data = pd.read_json('filename.json',dtype='int64') data = da ...

Having issues with the <ul> tag not displaying correctly

I'm currently working on implementing a side navbar for my website, but I've run into an issue with spacing. In the demo linked in my fiddle, you'll notice that the <ul> element inside the receiptDropDown class doesn't push the k ...

Layering elements using the z-index property in Internet Explorer 7,

Issue with text placement in a dialog div only occurring in IE 7. To see the problem, visit this page and click on any of the text boxes on the left side. Attempts to fix by adjusting z-index in the skin.css file for div.dialogFromAndTo did not resolve ...

Creating clickable data columns in jQuery DataTablesWould you like to turn a column in your

How can I turn a column into a clickable hyperlink in a jQuery DataTable? Below is an example of my table structure: <thead> <tr> <th>Region</th> <th>City</th> <th> ...

Continuous front-end promise awaiting response from back-end Node.js function

Currently, I am working on a basic React frontend where I need to fetch some data from my backend API powered by Node.js. This backend API calls an external API to get the required data. Although I have verified that the data is fetched successfully on the ...

What steps should I take to optimize the performance of this code by implementing rate-limiting for its execution speed?

As I pondered the task at hand, I realized that using a sleep function might be beneficial. However, Javascript lacks a built-in sleep function. How can I tweak this process to avoid hitting a Parse rate-limit? My goal is to execute one (1) Parse.Cloud.ru ...

What is the best way to demonstrate that every key within an object possesses the identical type?

I received a JSON response containing various metrics along with their values and confidence levels. I want to represent this data as a JSON Schema and generate beans using JsonSchema2Pojo. { "QPI": { "value": 0.053916827852998075, "co ...

Creating a website with a seamless image background that fills the entire page

! Is it possible to achieve the same effect using AngularJS? Below is the CSS code: .bg { background: url(holiday-car-rental.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-s ...

Internet Explorer experiencing difficulties displaying elements

On occasion, my website (find-minecraft-servers.com) may appear distorted in Internet Explorer. Sometimes, the number under Servers Listed in the green-ish banner fails to display correctly, despite being present in the source code. This issue seems to be ...

Something seems to be preventing Div from appearing and there are no error messages appearing

I've been attempting to create a menu, but the toggle div for the menu isn't visible Following a tutorial where an individual sets up a menu, there is a div with a menu icon in the top left corner. Despite meticulously copying the code from the ...

Tips for detecting if text appears in bold on a webpage using Selenium

I came across a pdf document with the following content: <div class=**"cs6C976429"** style="width:671px;height:18px;line-height:17px;margin-top:98px;margin-left:94px;position:absolute;text-align:left;vertical-align:top;"> <nobr ...

The functionality of CSS columns is not supported in Firefox browser

Currently, I am working on a web page design inspired by Pinterest. However, I have encountered an issue where the columns property is not functioning properly in Firefox. You can find the example I am trying to replicate here. Feel free to test it in Fir ...

If the request body exists, it should return a 409 error code

*Can anyone please help me with avoiding duplicate requests for existing names in NodeJS Express?* Here is my code: /* Post new person to persons */ app.post("/api/persons/", (req, res) => { const schema = { name: Joi.string().alphanum ...

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 ...

Safari is not functioning properly with the css display:none property

My HTML code looks like this: <div id="loadinganimationsearch"> <div style="color: #28ABE3;font-size: 14px;float: left;">Fetching Textbooks</div> <div id="block_1" class="barlittle"></div> <div id="block_2" ...

What is the best way to split text copied from a textarea into <p> paragraphs with an equal number of characters in each?

Check out this JSFiddle version I've found a JSFiddle example that seems perfect for my current project needs. However, I'm wondering how to modify the code to ensure that each paragraph is evenly divided with the same number of characters and a ...

Tailwind CSS - when it comes to styling, larger screen media queries are taking precedence over smaller media queries

Currently tackling screen responsiveness issues in a Nextjs + Tailwind CSS project. All Tailwind breakpoints are functioning correctly except for "sm" and below. Snippet of the problematic code: <div className="bg-red-200 sm:bg-white md:bg-gray-70 ...