最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery replace dots with spaces inside of all DIVs with one class - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question asked Jan 6, 2012 at 9:35 CamSpyCamSpy 4012 gold badges15 silver badges26 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

You can use each() to iterate over the matched elements, or pass a function to html() and pute the new text there:

$(document).ready(function() {
    $(".title").html(function(index, currentHtml) {
        return currentHtml.replace(/\./gi, " ");
    });
});

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

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/jZgUY/

发布评论

评论列表(0)

  1. 暂无评论