views:

34

answers:

2

I am trying to use JQuery to search and replace all instances of a given string. JQuery was the only method I found which doesn't force-reload the whole page. This is what I have right now:

<script>
$("*").each(function () { 
   if ($(this).children().length == 0) { 
      $(this).html($(this).html().replace('0101','0102')); 
   } 
});
</script>

Right now, this replaces most instances of 0101 with 0102 on the page, but it does not replace instances within href links. Does anyone know why? I really need this to find/replace the whole document, through and through.

+1  A: 

Add this

$(this).attr('href', $(this).attr('href').replace('0101','0102'));

The .html() method is only going to replace the html within an element.

.attr() allows you to access the attributes of an element which of course the href is.

Rigobert Song
he is using `$(this).html()` witch would return the element as text such as `<a href="...">...</a>` there for it would replace correctly.
RobertPitt
This didn't work. At what point exactly do I add this code in? Could you post the whole code you suggest?
Julien
A: 

I believe that your problem lies in the use of .replace(). If you use a string as the search-value, only the first occurrence is replaced. You need to use a regular expression with the global-flag for this:

$(this).html($(this).html().replace(/0101/g,'0102')); 
elusive
This didn't work either.
Julien
Have a look at this example: http://jsfiddle.net/2BKnz/ I think selecting the body will fit your intention. Let me know if this works for you.
elusive
When I put this code into my site, it goes through an infinite loading loop.
Julien
Interesting problem. Can you provide a link to this site?
elusive