Reputation: 401
I am using latest Jquery and the following script:
<script type="text/javascript">
$(document).ready(function(){
var el = $('.title');
el.html(el.html().replace(/\./gi, " "));
});
</script>
This is the div:
<div class="title">The.quick.brown.fox</div>
What it does is replaces all dots with spaces in a DIV with class "title" and really it works fine for this job.
But I have many DIVs with the same "title" class with different strings in them and i need them all to have dots replaced with spaces. But here the problem appears as all what i get is the same result string on all these DIVs "The quick brown fox" while all result strings should be different as all source strings are different...
What do i do to get dots replaced in all DIVs with class "title" and all different strings in each DIV?
Thanks
Upvotes: 2
Views: 5088
Reputation: 214959
As long as you have only text inside your divs, suggested functions will work just fine. However, to allow arbitrary html (like The.quick.brown <img src='fox.jpg'>
) the code should be more accurate.
$('.title').each(function() {
if (this.nodeType == 3)
this.nodeValue = this.nodeValue.replace(/\./g, " ");
else
$(this).contents().each(arguments.callee);
});
Basically, you recursively iterate over all descendants of a node and replace only nodes of type 3 (=text).
Fiddle: http://jsfiddle.net/jZgUY/
Upvotes: 1
Reputation: 262939
You can use each() to iterate over the matched elements, or pass a function to html() and compute the new text there:
$(document).ready(function() {
$(".title").html(function(index, currentHtml) {
return currentHtml.replace(/\./gi, " ");
});
});
Upvotes: 5
Reputation: 22943
Just use jQuery each
method to iterate over all elements with class .title
:
$(document).ready(function(){
$('.title').each(function(){
$(this).html($(this).html().replace(/\./gi, " "));
});
});
Upvotes: 2