8

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.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
Dimskiy
  • 5,233
  • 13
  • 47
  • 66
  • 1
    I'm not sure why Karim deleted his answer, so I'm placing this in a comment. 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 Jul 16 '10 at 20:35

2 Answers2

7
$(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.

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • Thank you, jAndy. I'm having trouble setting text to it's new value. The .text('new value') just doesn't do anything. – Dimskiy Jul 16 '10 at 20:49
  • 1
    @dimskiy: indeed, `.replaceWith()` does also perform well. – jAndy Jul 16 '10 at 20:58
  • I had a hard time choosing between the 2 solutions. Choosing yours for .replaceWith(). I actually have cases where certain chars need to be replaced by html elements, and .replaceWith() does the trick. Thank you! – Dimskiy Jul 16 '10 at 21:09
4

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.

lucideer
  • 3,842
  • 25
  • 31
  • Thank you, lucideer. I have jQuery already in that project, so a jQuery solution is fine as well. I can't set text using .wholeText. I get Error: setting a property that has only a getter – Dimskiy Jul 16 '10 at 20:51
  • Update: nodes[i].data will render html tags as text. – Dimskiy Jul 16 '10 at 21:10
  • Sorry about that dimskiy - you're right, my reply was incorrect about setting the wholeText - edited. You can't put HTMLElements into a textNode, but you can remove the textNode and replace it with a HTMLElement (or a series of them). – lucideer Jul 16 '10 at 22:43