<div id="id1">
apple
ball
dogsss
dogsssdogsss
dogsssdogsssdogsss
</div>
How Do I change ALL dogsss to dollsss using jquery?
Here is a code, but how to determine the element?
$('#id1 how???').each(function() {
var text = $(this).text();
$(this).text(text.replace('dog', 'doll'));
});
Here is similar question http://stackoverflow.com/questions/8146648/jquery-find-text-and-replace
Your replace will only remove first occurrence from the string. Use regex with replace to remove all occurrences. Use global flag i.e. g in the regex to replace all occurrences.
Change
$(this).text(text.replace('dog', 'doll'));
To
$(this).text(text.replace(/dog/g, 'doll'));
Also, you can use text() with callback to update the innerText of element.
Demo
$('#id1').text(function(i, oldText) {
return oldText.replace(/dog/g, 'doll');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="id1">
apple ball dogsss dogsssdogsss dogsssdogsssdogsss
</div>
You should use the '/g' for global in your regular expression. Otherwise only the first match gets replaced.
$(this).text(text.replace(/dog/g, 'doll'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With