I have an article with many instances of the word "color". I set up a button with the class .colour so that if you want you can click it and change the spelling from "color" to "colour" throughout the page. I've written some jQuery to do this but it only changes one instance of the word color but not all. You'd have to keep repeatedly clicking the button to change all of them.
$(document).ready(function(){
$(".colour").click(function(){
$("body").children().each(function() {
$(this).html($(this).html().replace("color","colour"));
});
})
})
Is there a way to repeatedly loop the script until it changes all instances? Also is it possible to make it so it is not case-sensitive? I'm new to javascript and jquery so might be a noob question. Thanks
Here's a codepen of it: http://codepen.io/patrickaltair/pen/vcdmy
The replaceAll() method is an inbuilt method in jQuery which is used to replace selected elements with new HTML elements. Parameters: This method accepts two parameter as mentioned above and described below: content: It is the required parameter which is used to specify the content to insert.
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.
We can replace HTML elements using the jQuery . replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.
Have your replace use a regex with a global replace.
Change:
$(this).html().replace("color","colour")
to:
$(this).html().replace(/color/g,"colour");
codepen example
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