开发者

Select only text of an element (not the text of its children/descendants)

开发者 https://www.devze.com 2023-01-07 21:33 出处:网络
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

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开发者_如何学Python 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.


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

精彩评论

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