最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Select only text of an element (not the text of its childrendescendants) - Stack Overflow

programmeradmin0浏览0评论

Please consider the following HTML:

<td>
  Some Text
  <table>.....</table>
</td>

I need to manipulate the "Some Text" text of td element. I should not touch the table element inside of this td.

So, just for example, maybe I want to replace all "e" with "@". I tried a few approaches with jQuery's .text() and .html(). I seem to always select something from within the child table, which I shouldn't touch. Also, unfortunately, I cannot wrap "Some Text" into a span or a div.

Please consider the following HTML:

<td>
  Some Text
  <table>.....</table>
</td>

I need to manipulate the "Some Text" text of td element. I should not touch the table element inside of this td.

So, just for example, maybe I want to replace all "e" with "@". I tried a few approaches with jQuery's .text() and .html(). I seem to always select something from within the child table, which I shouldn't touch. Also, unfortunately, I cannot wrap "Some Text" into a span or a div.

Share Improve this question edited Nov 22, 2011 at 18:43 Phrogz 304k113 gold badges667 silver badges757 bronze badges asked Jul 16, 2010 at 20:16 DimskiyDimskiy 5,30113 gold badges49 silver badges69 bronze badges 1
  • 1 I'm not sure why Karim deleted his answer, so I'm placing this in a ment. What's wrong with $('#myCell')[0].firstChild.data = $('#x')[0].firstChild.data.replace('e', '@');. The only thing I can see is it might not inculde all text objects. – Yuriy Faktorovich Commented Jul 16, 2010 at 20:35
Add a ment  | 

2 Answers 2

Reset to default 7 +500
$(function(){
  $('td').contents().each(function(){
     if(this.nodeType === 3)
      $(this).replaceWith(this.wholeText.replace(/e/g, '#'));
  });
});

or like you suggested

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

.contents() delivers all elements, textNodes included.

If you want to do something for each piece of text in the td, you could just iterate over them with a loop:

var nodes=tdEl.childNodes;
for(var i=0; i<nodes.length; ++i){
  if(nodes[i].nodeType===3){  // 3 means "text"
    nodes[i].data = nodes[i].wholeText.replace(/e/g, '@');
  }
}

Did I understand what you were looking for correctly?

You could use jQuery if you're already loading it for other stuff, but I wouldn't load in a 24kb library for the small bit of code above.

发布评论

评论列表(0)

  1. 暂无评论