仅选择元素的文本(不是其子元素/后代的文本)

Dim*_*kiy 8 html javascript jquery

请考虑以下HTML:

<td>
  Some Text
  <table>.....</table>
</td>
Run Code Online (Sandbox Code Playgroud)

我需要操纵td元素的"Some Text"文本.我不应该触摸里面的表格元素td.

所以,例如,也许我想用"@"替换所有"e".我用jQuery的.text()和.html()尝试了一些方法.我似乎总是从子表中选择一些我不应该触摸的东西.另外,遗憾的是,我无法将"Some Text"包装成span或div.

jAn*_*ndy 7

$(function(){
  $('td').contents().each(function(){
     if(this.nodeType === 3)
      $(this).replaceWith(this.wholeText.replace(/e/g, '#'));
  });
});
Run Code Online (Sandbox Code Playgroud)

或者像你建议的那样

$('td').contents().each(function(){
  if(this.nodeType === 3)
     this.data = this.wholeText.replace(/e/g, '#');
 });
Run Code Online (Sandbox Code Playgroud)

.contents()提供所有元素,包括textNodes.