admin管理员组文章数量:1318996
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
2 Answers
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.
本文标签: javascriptSelect only text of an element (not the text of its childrendescendants)Stack Overflow
版权声明:本文标题:javascript - Select only text of an element (not the text of its childrendescendants) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742053615a2418176.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论