1

HTML Code

<td class='money'>192.13</td><td class='money'>85.23</td>

Task

I would like to replace in the content of all cells with class money the "." with ","

Solution1

var value = $(".money").html(); 
value = value.replace(".", ","); 
$(".money").html(value);

Problem: The value of the first value is replacing all other values.

Solution2

$(".money").html().replace(".",",");

Problem: does not work

3 Answers 3

4

You need to use a setter version of .html()

$(".money").html(function(i, html){
    return html.replace(".",",")
});

your code returns a replaced string for the first td, but it is not set back to the cell.

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

Comments

3

So, $('.money') is a collection of all of the DOM elements that match your selector, which is why solution #1 doesn't work. Therefore, you need to look through each of the matched elements and perform your operation individually:

$.each($('.money'), function() {
  // $(this) refers to the current matched element in the loop
  var $this = $(this),
    value = $this.html().replace(".", ",");

  $this.html(value);
};

After posting, I saw Arun's answer, and it is sexier, so go with that. But I think you could stand to learn from the concepts explained in my answer.

Comments

3

To try and help you understand why it doesn't work, let's read your code:

  • Find all .money elements, and get the html of the first one.
  • Replace the . with a ,
  • Find all .money elements, and set their html to that first value.

Second code:

  • Find all .money elements, and get the html of the first one.
  • Replace the . with a ,
  • Do bugger all.

This is one of the many problems I have with jQuery: ambiguous functions. .html() returns the HTML of the first element in the set, but .html(value) replaces the HTML of all elements in the set.

Anyway, the jQuery you're looking for is:

$(".money").each(function() {
    var $this = $(this);
    $this.html($this.html().replace(".",","));
});

Consider also this Vanilla JS:

[].forEach.call(document.querySelectorAll(".money"),function(e) {
    e.innerHTML = e.innerHTML.replace(".",",");
});

While is may look like more or messier code, it is many many times faster than any jQuery solution.

And finally, a hybrid solution that combines performance with browser compatibility:

$(".money").each(function() {
    this.firstChild.nodeValue = this.firstChild.nodeValue.replace(".",",");
});

Enjoy!

Comments

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.