1

I am trying to get Javascript to read and write a paragraph based on content elsewhere on the page (specifically the names of items in a cart summary). The problem is that I can't get Javascript to write them correctly.

I need the being written paragraph to be "Order Includes: Product 1, Product 2, etc." but instead it is returning "Order Includes: [object HTMLParagraphElement], [object HTMLParagraphElement], etc."

<!-- Cart Summary -->
<p class="cartitems" id="Quantity">Product 1</p>
<p class="cartitems" id="Quantity">Product 2</p>

<!-- Paragraph to be written -->     
<p id="printItems"></p>

<script>
  var prods = document.getElementsByClassName("cartitems");
  var items = Array.from(prods);
  document.getElementById("printItems") = "Order Includes: " + 
  items;
</script>

I've tried using

var prods = document.getElementsByClassName("cartitems").innerHTML;

and

document.getElementById("printItems").innerHTML = "Order Includes: " + 
  items;

But both return undefined.

  • 1
    Possible duplicate of [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Heretic Monkey Jul 11 '19 at 20:11

2 Answers2

2

The Document.getElementsByClassName() method returns a collection of DOM elements. When you convert the HTMLCollection, returned by the method, to an array with Array.from(), use the callback to get the innerText from the elements:

var prods = document.getElementsByClassName("cartitems");
var items = Array.from(prods, el => el.innerText);
document.getElementById("printItems").innerHTML = "Order Includes: " +
  items.join(', ');
<!-- Cart Summary -->
<p class="cartitems" id="Quantity">Product 1</p>
<p class="cartitems" id="Quantity">Product 2</p>

<!-- Paragraph to be written -->
<p id="printItems"></p>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

What document.getElementsByClassName is returning is an HTMLCollection (HMTLCollection MDN Docs)

This is a direct element which is part of the DOM. So you can not parse it directly to an array, you can use the following method to parse to your desired array:

var prods = document.getElementsByClassName("cartitems"); var parsedArray = Array.from([].slice.call(prods)); document.getElementById("printItems") = "Order Includes: " + items;

As suggested on Harpo response (Harpo response)

NOTE: using Array.from on this case would be optional because what slice returns is an array by its own.

JGuarate
  • 378
  • 3
  • 9