0

Basically I have below span:

<span id="test">hello <span id="what">john</span>, How are you?</span>

I just want to change the text of test span without removing the it's children/whatspan.

I tried jquery text() function, but that seems to remove the children.

See demo here: https://jsfiddle.net/rf9x7zq3/4/

whocaresz
  • 17
  • 4

2 Answers2

1

Why not put "hello" inside a span of its own and only alter its content?

HTML

<span id="test"><span id="greeting">hello </span><span id="what">john</span>, How are you?</span>

JS

$(document).ready(function(){
    $('#greeting').text('hi');
});
Viriato
  • 141
  • 4
1

You can do it like so:

let test = document.getElementById("test");
for (let child of test.childNodes) {
  if (child.nodeType === 3) {
    child.textContent = " hi ";
  }
}
<span id="test">hello <span id="what">john</span>, How are you?</span>

Basically you loop through the child nodes of your span that are text child.nodeType === 3 and then you can update their content. In the snippet above I'm just replacing all the text nodes with "hi" and leaving the inner span id "what" as is. You can change to whatever text you wish those child text nodes.

Luís Ramalho
  • 10,018
  • 4
  • 52
  • 67