开发者

Remove all occurence of anchor tags from a string, while preserving their inner text nodes

I have an HTML string. I'd like to transform 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>           
  &开发者_运维百科lt;/tr>
</table>

Into this:

<table >
  <tr>
      <td>some text</td>
      <td>some more text</td>           
  </tr>
</table>


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.


$(function(){
$('td a').each(function(){
   $(this).replaceWith($(this).text());
});
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜