update innerText without deleting child nodes
Asked Answered
T

1

6

I have a div with some text and a child div. I want to update the outer div text and keep the child div.

<div class="outer">
  some text here
<div class="arrow-down"></div>
</div>

if I try outer.innerText = "foo" the arrow-down element is deleted. How can I get around this?

Thanks

Transcendental answered 13/12, 2017 at 16:34 Comment(6)
Put your text in an element, e.g. a span and then edit that?Shroudlaid
Use a span element as the first child of the outer div, assign an ID to it and target that span element when updating the text.Archibaldo
which is child div?Hydrastis
Your arrow down Div is not inside the outer div in your example - thus is not in a parent-child relationship in the context that you have providedPeary
Seems something is missing. Are you using "outer" anywhere else? Is the div with the "outer" class all that remains when you use outer.innerText and arrow-down is deleted?Torrens
my mistake - arrow-down was suppsoed to be inside outerTranscendental
A
2

Create a child element such as a span element and place the text you want change inside that.

Then you can update that via JavaScript like so:

var el = document.getElementById('inner');
el.innerText = 'some different text';
<div class="outer">
  <span id="inner">some text here</span>
  <div class="arrow-down"></div>
</div>
Archibaldo answered 13/12, 2017 at 16:40 Comment(3)
thanks, I'll do this as it appears to be the only optionTranscendental
It isn’t necessarily the only option. For example, you could also parse the HTML out of the div’s innerHTML property and swap in your new text using regular expressions... but that would be more difficult and less flexible. Using the additional span to compartmentalize your text is always BETTER because it opens you up to more options, such as unique styles between the span and its sibling tags.Disrobe
This should answer your question maybe... https://mcmap.net/q/151393/-how-can-i-change-an-element-39-s-text-without-changing-its-child-elementsDecasyllabic

© 2022 - 2024 — McMap. All rights reserved.