Home > Net >  Selecting and adding values found with getElementsByClassName to dict or list
Selecting and adding values found with getElementsByClassName to dict or list

Time:10-27

I am very new to JavaScript and I am trying to use it to select values from HTML using document.getElementsByClassName by putting index [0] from HTMLCollection. There is either one instance of the class being present or two or more.

const pizzatype = document.getElementsByClassName("pizzapizza")[0].innerHTML;
const pizzacheese = document.getElementsByClassName("cheesecheese")[0].innerHTML;
const pizzasauce = document.getElementsByClassName("saucesauce")[0].innerHTML;
const ordertotal = document.getElementsByClassName("fiyat")[0].innerHTML;

const order_dict = {
  pizzatype,
  pizzacheese,
  pizzasauce,
  ordertotal
}
const s = JSON.stringify(order_dict);
console.log(s); // returns {"pizzatype":"value1","pizzacheese":"value2","pizzasauce":"value3","ordertotal":"value4"}

The class is set like this:

<div >${pizza.cheese}</div>

I tried experimenting with for loop, index(), .length, and others but I never got it to work. What would be the way to go to get return:

{
  "pizzatype": "valuex1",
  "pizzacheese": "valuex2",
  "pizzasauce": "valuex3",
  "ordertotal": "valuex4",
  "pizzatype": "valuey1",
  "pizzacheese": "valuey2",
  "pizzasauce": "valuey3",
  "ordertotal": "valuey4"
}

It should work even when there are more than 2 instances of those classes.

CodePudding user response:

There is no way to store same key multiple times in Javascript object. You can use Entries syntax instead to get something similar.

Example of entries

[
 [“pizzatype”, firstval],
 [“pizzatype”, secondval],
]

Or you can use array of values inside your object.

To get result like so

{
  pizzatype: [firstval,secondval],
  …
}

You can get it with this way

{
  pizzatype: Array.from(document.getElementsByClassName(“pizzapizza”)).map(elem => elem.innerHTML)
}
  • Related