I curreny use the following script to find and replace text on my website.
$("#content #tablelabel p").text(function (_, ctx) { return ctx.replace("Check In", "入住"); });
But there are hundreds of words to find and replace. Some of them share the same CSS path. Can you guys please tell me how to optimise that script and create a function to pass the CSS path and word to find and replace so I can eliminate repetition of the same scripts?
Also is it possible to pass multiple words to find with their replacement text. For an example without writing
$("#content #tablelabel p").text(function (_, ctx) { return ctx.replace("Room Type", "入住"); });
$("#content #tablelabel p").text(function (_, ctx) { return ctx.replace("Guests", "退房"); });
Can I do soemthing like
$("#content #tablelabel p").text(function (_, ctx) { return ctx.replace({'Room Type': '房间类型','Guests': '房间类型'}); });
Thanks
To change text inside an element using jQuery, use the text() method.
You can iterate over an object an replace all the values in it like
var tags = {
'Room Type': '入住',
'Guests': '退房'
};
$("#content #tablelabel p").text(function(_, ctx) {
$.each(tags, function(tag, text) {
ctx = ctx.replace(tag, text);
})
return ctx;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<div id="tablelabel">
<p>Room Type</p>
<p>Guests</p>
</div>
</div>
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