tags:

views:

105

answers:

5

I'm desperately looking for a jQuery function to parse every string in a page (may be in a table) and replace its content with another one.

For example, i want to uppercase any string that is in a table row.

Couldn't find any clue on how to get started, would appreciate some starter help.

+1  A: 

I do not know of a plugin that performs this task, but maybe this could be useful.

$("#mytable").replaceTableContents(origText, newText)

(function($){
$.fn.replaceTableContents = function(old, newt)
{
  if($(this).text().indexOf(old)>-1){ //check
    $(this).find("tr").each(function(){

      if($(this).text().indexOf(old)>-1){ //check

         $(this).find("td").each(function(){

            if($(this).text().indexOf(old)>-1){ //check
               $(this).html($(this).html().replace(old, newt));
            } 

         }
      }

    })
  }
}
})(jQuery);
andres descalzo
Just what i was looking for. Many thanks
Disco
+1  A: 

You could use a query like this to get all text nodes and then do a loop over the collection. I would probably limit it just to the element that has the text you want to modify and not do it on 'body' as it probably will not be very performant.

var nodes = $("body")
              .contents()
              .filter(function() {
                  return this.nodeType == Node.TEXT_NODE;
              });
joshperry
+1  A: 

The following will navigate over all the elements on the page, checking for text nodes. You can then do something with them.

$(document).contents()
           .filter( function() { return this.nodeType == 3 } )
           .each( function() {
               ...process...
           });

To uppercase any string inside a table, though, I would use

$('table').contents().
          .filter( function() { return this.nodeType == 3 } )
          .each( function() {
              this.innerHTML = this.innerHTML.toUpperCase();
          });
tvanfosson
Cool, is there a link you can provide to see what other nodeType's you can test for?
RedWolves
http://www.w3schools.com/Dom/dom_nodetype.asp
tvanfosson
+1  A: 

Someone correct me if I'm wrong but with jQuery you don't need to iterate over anything to find table rows. In this case:

CSS

tr.upper{text-transform:uppercase}

jQuery Script

$(document).ready(function(){
    $("tr").addClass("upper");
});
jeerose
+1  A: 

There are some good answers here but remember that whatever you do, it will be imperfect because any word containing markup will appear as a normal word to the user, but will not match your search pattern.

e-satis