[英]Select only text of an element (not the text of its children/descendants)
請考慮以下HTML:
<td>
Some Text
<table>.....</table>
</td>
我需要操縱td
元素的“Some Text”文本。 我不應該觸摸這個td
里面的table元素。
所以,例如,也許我想用“@”替換所有“e”。 我用jQuery的.text()和.html()嘗試了一些方法。 我似乎總是從子表中選擇一些我不應該觸摸的東西。 另外,遺憾的是,我無法將“Some Text”包裝成span或div。
$(function(){
$('td').contents().each(function(){
if(this.nodeType === 3)
$(this).replaceWith(this.wholeText.replace(/e/g, '#'));
});
});
或者像你建議的那樣
$('td').contents().each(function(){
if(this.nodeType === 3)
this.data = this.wholeText.replace(/e/g, '#');
});
.contents()
提供所有元素,包括textNodes 。
如果你想為td中的每一段文本做一些事情,你可以用循環迭代它們:
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, '@');
}
}
我理解你正在尋找什么嗎?
你可以使用jQuery,如果你已經為其他東西加載它,但我不會在24kb庫中加載上面的一小段代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.