-1

I want to use JavaScript/JQuery to modify the text of an HTMLElement without affecting the child HTMLElements.

I have html that looks like:

<span class="js-my-parent-span">
    "Hello, World!"
    <span class="js-my-child-span">
    </span>
</span>

I have attemted to change the Hello, World! text using the innerHTML and innerText attributes as well as the html() method from JQuery. All of these methods also overwrite the child span.

I just want to update the text.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36
  • Then update the text node and stop trying to change the content of the whole span. – Kevin B Jun 23 '16 at 18:49
  • `theEl.contents().get(0).textContent = 'foo'`. or even better, `theEl[0].childNodes[0].textContent = 'foo'` – Kevin B Jun 23 '16 at 18:55
  • You can mark one of answer to finishing this discussion. – Mohammad Jul 03 '16 at 21:18
  • Does this answer your question? [How can I change an element's text without changing its child elements?](https://stackoverflow.com/questions/4106809/how-can-i-change-an-elements-text-without-changing-its-child-elements) – DurandA Sep 16 '22 at 11:25

4 Answers4

1

You could wrap the text in its own container, which is probably the best pattern here.

$('.text-content').text('Something else')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="js-my-parent-span">
    <span class="text-content">Hello, World!</span>
    <span class="js-my-child-span">Other content</span>
</span>
Kyle Macey
  • 8,074
  • 2
  • 38
  • 78
1

You can get childs of span using childNodes property. childNodes[0] contain "Hello, World!" text.

$(".parent")[0].childNodes[0].nodeValue = "New hello world-";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="parent">
    "Hello, World!"
    <span>Child text</span>
</span>
Mohammad
  • 21,175
  • 15
  • 55
  • 84
1

You can target the first child node of the element, which is specifically the text node holding the content. However, if the span is mid-sentence, this will not work.

document.querySelector('button').onclick = function(){
  document.getElementById('test').childNodes[0].textContent = "It worked without changing "
}
<span id="test">Change this text without removing <span>what's in the span</span></span>
<button>Do It</button>
jmcgriz
  • 2,819
  • 1
  • 9
  • 11
1

var childs = $(".js-my-parent-span").find(".js-my-child-span");

$(".js-my-parent-span").html('"Hello, world i have successfully changed only the text and not the child element!" ').append(childs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="js-my-parent-span">
    "Hello, World!"
    <span class="js-my-child-span">This is child span
    </span>
</span>