-1
const categoriesLght = document.querySelectorAll('#categories .item').length;
console.log(`There are ${categoriesLght} clasifications.`);
const h2s = document.querySelectorAll('h2');
const heading = h2s.forEach(element =>
  console.log(`Clasification: ${element.textContent}`),
);

const quantity = document.querySelectorAll('h2 + ul');
quantity.forEach(el =>
  console.log(`Quantity: ${el.childElementCount}`),
);

Output:

There are 3 clasifications.
Clasification: Student
Clasification: Fish
Clasification: Rocket
Quantity: 3
Quantity: 5
Quantity: 6

If I try to put a function in a template string, there will be an error. Trying to find a way to make it happen. Desired output is:

Clasification: Student
Quantity: 3 
Clasification: Fish
Quantity: 5
Clasification: Rocket
Quantity: 6

And I'm looking for a way how to put a result of ForEach method in a template string, to make happen something like that (I think I'm looking for some destructurization):

str = [h2s.forEach, quantity.forEach]([category, count])=> (console.log(`Clasification: ${category.textContent},
Quantity: ${count.childElementCount} `));
ElMuchacho
  • 300
  • 1
  • 12

2 Answers2

1

Loop over one and use the index to reference the other

const h2s = document.querySelectorAll('h2');
const quantity = document.querySelectorAll('h2 + ul');

h2s.forEach((element, i) =>
  console.log(`Classification: ${element.textContent}, Quantity: ${quantity[i].childElementCount}`),
);
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

You could try saving the values to variable first:

const clarifications = [];
const quantities = [];

const h2s = document.querySelectorAll('h2');
const heading = h2s.forEach(element =>
    clarifications.push(element.textContent);
);

const quantity = document.querySelectorAll('h2 + ul');
quantity.forEach(el =>
    quantities.push(el.childElementCount);
);

clarifications.forEach((clarification, i) => {
    console.log('Clarification:', clarification);
    console.log('Quantity:', quantities[i]);
});
Paolo Carrara
  • 394
  • 4
  • 13