Ad

Represent Number As Currenct From Paragraph

- 1 answer

On my web page I have an paragraph which looks like this:

<p class="article-content mb-1" id="cost"><strong>Cost [Euro]: </strong>1000000</p>

Number is always something else (which I read from db and represent using Django forms) and I would like to represent it as currency (in this case 1.000.000). I tried to get the value with:

function on_load() {
  var a = document.getElementById('cost').value;
  console.log(a)
}
on_load();
<p class="article-content mb-1" id="cost"><strong>Cost [Euro]: </strong>1000000</p>

but Console output is: 'undefined'. When I get value, I'll use something like

(12345.67).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');  // 12,345.67

To convert to currency.

Ad

Answer

p does not have a value attribute. You can do this to get and format the number using intl number format

function on_load() {
  const costs = document.querySelector('#cost');
  let number = costs.childNodes[1].textContent;
  costs.childNodes[1].textContent = new Intl.NumberFormat('de-DE').format(number);
}
on_load();
<p class="article-content mb-1" id="cost"><strong>Cost [Euro]: </strong>1000000</p>

Ad
source: stackoverflow.com
Ad