0

I have a table

<table id="t">
     <tr>
           <td> fsabcdf </td>
           <td> xyzabcdf </td>
     </tr>
     <tr>
           <td> fsabcdf </td>
           <td> xyzabcdf </td>
     </tr>
     <tr>
           <td> fsabcdf </td>
           <td> xyzabcdf </td>
     </tr>
</table>

i want to replace "abc"(in td) with "abc" as in the following

<table id="t">
     <tr>
           <td> fs<span class='c2'>abc</span>df </td>
           <td> xyz<span class='c2'>abc</span>df </td>
     </tr>
     <tr>
           <td> fs<span class='c2'>abc</span>df </td>
           <td> xyz<span class='c2'>abc</span>df </td>
     </tr>
     <tr>
           <td> fs<span class='c2'>abc</span>df </td>
           <td> xyz<span class='c2'>abc</span>df </td>
     </tr>
</table>

i googled for the solution but didn't find any.

Thanks in advance.

5
  • It might be easier to handle this on the server. Is that a possibility here? Commented Dec 23, 2013 at 16:31
  • BTW - you didn't find any results because the implementation will probably be different for each use case... Commented Dec 23, 2013 at 16:32
  • No @Lix , I should work on only HTML,and Javascript(or jquery), my work is on view and i can't access controller or model. Commented Dec 23, 2013 at 16:33
  • @Lix, i found methods like wrap() in jquery but the problem is i am unable select part of text from td ( $(what to write here).wrap() ) Commented Dec 23, 2013 at 16:36
  • Yes - this is because the wrap() command operates on elements and not on parts of text. You won't be able to use wrap() in this case. Commented Dec 23, 2013 at 16:37

3 Answers 3

6

You can do:

$('td').html(function(i, html){
  return html.replace(/abc/g, '<span class="c2">abc</span>'); 
});

This goes through each <td>, looks at its text, then replaces every occurrence of abc with abc wrapped in the span you want.

Sign up to request clarification or add additional context in comments.

2 Comments

The second argument of the html callback function contains current HTML of the element, using that can be more efficient that creating jQuery objects (not the downvoter).
Thanks for your soutions @BillCriswell, its working but its replacing only first occurence of 'abc' in td, so i have changed that to replace(/abc/g, ''); Now its changing every occurence
2

Something like:

$('td').each(function () {
    $(this).html($(this).html().replace('abc', '<span class="c2">abc</span>'));
});

http://jsfiddle.net/Ru8XX/

1 Comment

this worked for me, not the marked answer
1

Try this:

$('#t td').each(function(){
    $(this).html( $(this).html().replace("abc","<span class='c2'>abc</span>") );
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.