Reputation: 23
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
Upvotes: 1
Views: 65
Reputation: 324620
To try and help you understand why it doesn't work, let's read your code:
.money
elements, and get the html
of the first one..
with a ,
.money
elements, and set their html
to that first value.Second code:
.money
elements, and get the html
of the first one..
with a ,
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!
Upvotes: 3
Reputation: 8154
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.
Upvotes: 3
Reputation: 388316
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.
Upvotes: 4