![](/img/trans.png)
[英]How to strike through a list item without disturbing other items in a html list using Javascript
[英]How to replace text in HTML Node without disturbing other child nodes?
我的結構是:
<th>0.12345<div id="someDiv"></div></th>
我需要用其他文本替換0.123456,而不刪除div。 使用innerHTML
和innerText
殺死所有內容。
我知道我可以先使用substr()
來剪切innerHTML,然后重新構建完整的內容,但有最簡單的方法嗎?
您需要選擇TextNode對象並重置其nodeValue
。 現在該怎么做。 你可以從div開始,因為你知道它是id。 然后你可以使用previousSibling
屬性獲得textNode。
像這樣的東西:
document.querySelector('#someDiv').previousSibling.nodeValue = 'TEST'
<table> <tr> <th>0.12345 <div id="someDiv">div</div></th> </tr> </table>
UPD 。 如果您想在div之前插入新的文本節點並支持這兩種方案,您可以這樣做:
var div = document.querySelector('#someDiv');
if (div.previousSibling) {
div.previousSibling.nodeValue = 'TEST1';
}
else {
div.insertAdjacentHTML('beforebegin', 'TEST2');
// or if you want verbose
// div.parentNode.insertBefore(document.createTextNode('TEST2'), div);
}
var th = document.getElementsByTagName('th')[0]; th.childNodes[0].textContent = "foo";
<table><th>0.12345<div id="someDiv">somediv</div></th></table>
不幸的是,jQuery並沒有為文本節點提供很好的支持,所以你應該使用childNodes
或XPath手動獲取它。
為了簡單起見,我將在span標記中包含您需要的內容並直接操作它。
HTML:
<th>
<span class="myValue">0.12345</span>
<div id="someDiv">div</div>
</th>
JS:
$(".myValue").html("XXX");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.