0

The code below correctly changes the text inside of an HTML element by rewriting the entire line of text. This is accomplished using textContent but innerHTML can also do this.

document.querySelectorAll(".box")[0].textContent = 'The number of dollars in my bank account is $1';
body {
  margin: 0;
  padding: 0;
}
 
.box {
  padding: 10px;
  font-size: 2rem;
  color: white;
  font-family: sans-serif;
  background-color: blue;
}
<div class="box">The number of dollars in my bank account is ?</div>

However is there a way to change just a portion of the text without having to rewrite the entire line? This probably isn't correct but something like .innerHTML[5, 10] that would change just those specifically targeted characters.

Put simply when Javascript is used to change text or tags inside of an element does it always rewrite the entire section? This might not be visible to the user but is that what always happens behind the scene? Thanks so much!

DR01D
  • 1,325
  • 15
  • 32

2 Answers2

1

Far better approach would be to change your HTML to something like

<div class="box">The number of dollars in my bank account is <span id='amount'></span>.</div>

Then you can easily change just the amount with js:

document.getElementById('amount').innerHTML = '5$';

So your website displays:

The number of dollars in my bank account is 5$.

If you want to stick to your approach, only way to do that would be to save the entire content into a string and then perform some search on it, either by substring, filter or regex. Then you would replace the elements you want and put the string back in the HTML.

anteAdamovic
  • 1,462
  • 12
  • 23
  • Your solution solved the problem in my test program perfectly. Thanks! However the project I'm actually working on is a text formatter. It formats text input live as the user types. I read the value in an `input` box, format the value and then overwrite the old value in the `input` box with the new formatted value. This technically works but I was hoping there was a better way. But just knowing that there isn't a better way is a big leap forward. At least I know I'm on the right track. Thanks! – DR01D Nov 10 '17 at 00:18
  • As I said, only other way is to manually read the value of the input in a string, process it in any way and put it back in when you're done. – anteAdamovic Nov 10 '17 at 00:19
  • Yep, that is what I'm doing right now. Thanks for helping me narrow it down! – DR01D Nov 10 '17 at 00:21
1

Use a nested span tag to display the dollar amount. Then you only have to update the span's text. And when you need the entire sentence you can just access the div.box 's textContent. It returns the textContent of all nested elements concatenated.