1

I'm trying to replace all the text in a DIV, including inside children without change any html tags. In my example, I would like to change all the 'Hello' by 'Hi'. Thanks a lot.

var changes = $('div').html().replace('Hello','Hi');

$('div').html(changes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <p class="hello">Hello World</p>
  Hello World<br>
  <span class="world">Hello World</span>
</div>
Bruno Landowski
  • 3,689
  • 2
  • 16
  • 24

1 Answers1

4

The replace with a string parameter is not capable of replacing more than once. You need RegEx with a g (global) flag to replace all.

var changes = $('div').html().replace(/Hello/g,'Hi');
$('div').html(changes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <p class="hello">Hello World</p>
  Hello World<br>
  <span class="world">Hello World</span>
</div>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252