How can I replace text in HTML Node without breaking other child nodes?
My structure:
<th>0.12345<div id="someDiv"></div></th>
I need to replace 0.123456 with different text without deleting the div. Uses innerHTML
and innerText
kills all content.
I understand that I can use substr()
to slice the innerHTML first and then restore the full content, but is there an easier way?
source to share
You need to select the TextNode object and reset it nodeValue
. Now how to do it. You can start with a div since you know its id. Then you can get the textNode with the property previousSibling
.
Something like that:
document.querySelector('#someDiv').previousSibling.nodeValue = 'TEST'
<table>
<tr>
<th>0.12345 <div id="someDiv">div</div></th>
</tr>
</table>
UPD . If you want to insert new text node before the 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);
}
source to share
var th = document.getElementsByTagName('th')[0];
th.childNodes[0].textContent = "foo";
<table><th>0.12345<div id="someDiv">somediv</div></th></table>
Unfortunately jQuery doesn't provide much support for text nodes, so you have to grab it manually using childNodes
or XPath.
source to share