1

I have a Javascript function to format numbers with thousands seperator. I have many Span tags with the same class in my HTML code and I want to apply to all of them.

<span class="money">here is the number</span>

<script type="text/javascript">
  function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>

How can I apply the Javascript on every span with this class?

0

3 Answers 3

3

Use .text(function(index, text)):

$('.money').text(function(index, old_value) {
    return numberWithCommas(old_value);
});

The given function is called for each element that matches the selector and its current text value is passed as the second argument; the returned value will become the new text contents.

Sign up to request clarification or add additional context in comments.

Comments

0

Get the collection, iterate:

var spans = document.getElementsByClassName("money");
for (var i = 0; i < spans.length; i++) {
    spans[i].innerHTML = numberWithCommas(spans[i].innerHTML);
}

Comments

0
$('.money').each(function(){
     $(this).text(numberWithCommas($(this).text());  
});

1 Comment

sorry, forgot to set the result to be the text of the element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.