0

I have the following HTML structure:

<div id="container">
  <b>Hello</b>
  World
</div>

and I'd like to replace World with Earth like this:

<div id="container">
  <b>Hello</b>
  Earth
</div>

I don't want to modify the <b>Hello</b> element at all.

I can grab the container like this:

var el = document.querySelector("#container")

which has three element in childNodes, the last of which is a textNode:

childNodes

Is there a way to replace the text in the last element without modifying the entire innerHTML or innerText?

var el = document.querySelector("#container")

console.log(el.childNodes)
<div id="container">
  <b>Hello</b>
  World
</div>
KyleMit
  • 30,350
  • 66
  • 462
  • 664
  • 2
    In your example `document.querySelector('#container').childNodes[2].nodeValue = 'Earth';` but you could iterate the NodeList looking for the appropriate node by type and value. – pilchard Apr 21 '23 at 21:44

0 Answers0