tags:

views:

212

answers:

2

Like the title says,

I want to be able to, on page load, search through the text located inside #wrapper.

If there is a "&" I want it to have a span tag applied to it and a class appended to that span. Ie: if it finds "hello & Welcome" it should end up like "hello <span class="amp">&</span> Welcome".

I did have some code Ive been trying but all didn't work, so pointless to include it. Any help would be great guys thanks.

EDIT: have been working with

<script type="text/javascript">  
    $(document).ready(function() { 
     $("#wrapper").html( $("#wrapper").html().replace(/&amp;/g, '<span class="amp">&amp;<"+"/span>') ); 
    }); 
</script>

this loads with an Error in firebug telling me it isn't a function:

$ is not a function $(document).ready(function() {

Edit: oops forgot to include my reference to jQuery..

this works.

<script type="text/javascript">  
    $(document).ready(function() { 
       $("#wrapper").html( $("#wrapper").html().replace(/&amp;/g, '<span class="amp">&amp;<"+"/span>') ); 
    }); 
</script>
+1  A: 

Have you looked at jquery.highlight? It seems that it does what you want - the correct way (by searching only within textnodes, etc)

$("#wrapper").highlight('&');

A little further explanation. Imagine the following scenario:

 <div id='wrapper'>This &amp; should become highlighted.  
    And a picture: <img src='momanddad.jpg' alt='Mom &amp; Dad' /></div>

The blanket regexp replace will catch both of those &amp; occurrences and return with:

 <div id='wrapper'>This <span class="amp">&amp;</span> should become highlighted.  
    And a picture: <img src='momanddad.jpg' alt='Mom <span class="amp">&amp;</span> Dad' /></div>

This is obviously going to break your img tag. The jquery highlight plugin will avoid that.

gnarf
Marty
gnarf
very true, thanks..
Marty
A: 

For ease of reading I would re factor to;

var html = $("#wrapper").text().replace(/&/g,'<span class="amp">&</span>');
$("#wrapper").html(html);

Although I supposes that's an extra call to the DOM.

paulb
That is just completely pointless. There's no reason to set a variable if you're only going to use it once.
Josh Leitzel
You're probably right, I just like things to be blindingly obvious :-)
paulb