Change content of all elements having same class using javascript

I have a few text elements on the page associated with the class .currency-text. I want to format the value of these elements with 3 digit comma separate.

I have already created a function named formatText() to format text.

function formatText(x) {
   return x.toString().replace(/B(?=(d{3})+(?!d))/g, ",");

How do I traverse through the document and format all the text elements which have the class .currency-text. I am new to DOM manipulation and don’t know what is the efficient way to do it.


Grab the elements with querySelectorAll and then iterate over them applying the formatted text to each element.

const elements = document.querySelectorAll('.currency-text');

elements.forEach(el => {
  el.textContent = formatText(el.textContent);