views:

37

answers:

2

I have an html string and I need help transforming this:

<table >
  <tr>
      <td><a href="/link.html" onclick="javascript:aFunction()">some text</a></td>
      <td><a href="/anotherlink.html">some more text</a></td>           
  </tr>
</table>

to this:

<table >
  <tr>
      <td>some text</td>
      <td>some more text</td>           
  </tr>
</table>
A: 
$(function(){
$('td a').each(function(){
   $(this).replaceWith($(this).text());
});
});
pixeline
sorry for the silly question as i don't understand jquery well. What i have is an actual string (var htmlstr = '<table>....';). How would this solution be used for the string htmlstr?
siimi
+1  A: 

In jQuery 1.4+, you can pass a function to .replaceWith(), like this:

​$("table a")​.replaceWith(function() { return this.innerHTML; });​

You can give it a try here.

If you literally have a string, and not elements, it would look like this:

var html = '<table>...{rest of string}...</table>';
var o=$(html).find('a').replaceWith(function(){ return this.innerHTML; }).end();​

You can try that version here.

Nick Craver
+1 For the edit to use innerHTML. Would be ideal if the code sample factored in the fact that he has an HTML string, not a DOM to work with.
Josh Stodola
@Josh - Good point and catch on the question, added a string version above :)
Nick Craver
@Nick Nicely done :)
Josh Stodola
this question is from my lack of jquery prowess but i am trying to manipulate a string of html (var htmlstr = '<table><tr>...';)
siimi
@user449996 - See the second example and demo (refresh the page if you don't see them), it shows how to do it with a string as well. If you don't want elements at the end, you still want a string, here's a version doing that: http://jsfiddle.net/nick_craver/f87z7/2/
Nick Craver
Wow! having hard time keeping up with the responses :-) Thanks all!
siimi
@siimi - welcome, and welcome to SO :)
Nick Craver