Home > Back-end >  Change content of all elements having same class using javascript
Change content of all elements having same class using javascript

Time:10-24

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.

CodePudding user response:

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);
});

CodePudding user response:

From my understanding, you can find all elements associated with that class .currency-text and iterate on that returned list. Something is like:

let elements = $(document).find('.currency-text');
elements.each((e) => { e.innerText = formatText(e.innerText); });
  • Related