I nee...">

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?

+3


source to share


3 answers


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>
      

Run codeHide result


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);
}

      

+4


source


var th = document.getElementsByTagName('th')[0];
th.childNodes[0].textContent = "foo";
      

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

Run codeHide result




Unfortunately jQuery doesn't provide much support for text nodes, so you have to grab it manually using childNodes

or XPath.

+2


source


I would 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");

      

0


source







All Articles