3

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

jj1111
  • 607
  • 2
  • 10
  • 20

1 Answers1

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>
Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
Luke Stoward
  • 1,480
  • 14
  • 24
  • thanks, I'll do this as it appears to be the only option – jj1111 Dec 13 '17 at 16:48
  • 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. – Dom Ramirez Dec 13 '17 at 20:34
  • This should answer your question maybe... https://stackoverflow.com/a/4106910/1108235 – Ashish Apr 08 '21 at 19:53