简体   繁体   中英

How to replace text in HTML Node without disturbing other child nodes?

My structure is:

<th>0.12345<div id="someDiv"></div></th>

I need to replace 0.123456 with other text, without deleting div. Using innerHTML and innerText kills all the th content.

I understand that I can use substr() to cut the innerHTML first and then reconstruct the full content, but is there the simplest way?

You need to select TextNode object and reset its nodeValue . Now how to do it. You can start from the div, as you know it's id. Then you could get textNode with previousSibling property.

Something like this:

 document.querySelector('#someDiv').previousSibling.nodeValue = 'TEST' 
 <table> <tr> <th>0.12345 <div id="someDiv">div</div></th> </tr> </table> 

UPD . In case you want to insert new text node before div and support both scenarios you can do this:

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> 

Unfortunately, jQuery does not give great support for text nodes, so you should grab it manually using childNodes or XPath.

I'd wrap the content you need in a span tag and manipulate it directly for simplicity.

html:

<th>
    <span class="myValue">0.12345</span> 
    <div id="someDiv">div</div>
</th>

js:

$(".myValue").html("XXX");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM