-1

I want to get the value of multiple paragraphs with the same Class, but different content (numbers).

In detail these paragraphs contain numbers which I want to build a total and output it into another paragraph. The value of the paragraph is delivered by the CMS (Webflow). I can't work with native var in the script.

So I guess I have to build an Array and get the total. + Out put it with .innerHTML.

I'm new to JavaScript.

<p class="mwst-price" id="mwst-price"></p>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
    var tax = {totalPrice}+sums*0.19;
    document.getElementById("mwst-price").innerHTML = tax;
</script>
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Chris Code
  • 49
  • 5
  • 1
    `multiple items with the same ID` is a gross violation f HTML code. No two elements should have same ids, else you'll have errors like this. Can you have two individuals with the same identification number? – HymnZzy Feb 08 '21 at 14:45
  • An ID should be unique within a page. However, if more than one element with the specified ID exists, the getElementById() method returns the first element in the source code. - W3School – danhuong Feb 08 '21 at 14:46
  • @HymnZzy thanks +1. Your right, but how else could I get the value? or reference the object? – Chris Code Feb 08 '21 at 14:49
  • `getElementsByClassName` or `querySelectorAll`, and then you loop over the elements in the returned list. – CBroe Feb 08 '21 at 14:52
  • `document.querySelectorAll(...)` allows you to use CSS selectors and returns an array of elements. If you are using jQuery, you can simply use `jQuery(...)` to get the same result. – HymnZzy Feb 08 '21 at 14:53

2 Answers2

2
let totalPrice = 0;
document.querySelectorAll('p.myClass').forEach((paragraph) => {
  totalPrice += parseInt(paragraph.innerText);
});

const tax = totalPrice+sums*0.19;
document.querySelector('#mwst-price').innerHTML = tax;
Josh
  • 159
  • 9
0

Probably you need something like this, where "origin" is the class of the elements you want to sum up.

  function getNumberFromInnerHTML(el) {
    let value = el.innerHTML;
    // convert to number
    value = Number(value.replace(/[^0-9.-]+/g,""));
    return value;
  }
  
  let totalPrice = 0;
  document.getElementsbyClassName('origin').forEach(el => {
    totalPrice += getNumberFromInnerHTML(el);
  }

See this answer for converting a currency string to a number.

CimChd
  • 191
  • 6