I have some jQuery code:
jQuery('.lang-in-serach-blg').contents().filter(function() {
return this.nodeType == 3
}).each(function(){
this.textContent = this.textContent.replace('English','<img src="flags/24/en.png">');
});
I want to replace the text I want with an image, but this code displays the image URL instead of replacing the image. What should I do?
I also need this to work with multiple replacements. For example, I want to replace "English" with a flag, and later I want to replace "Francais" with another flag.
1 Answer 1
In order to add <img> tags, you use must .innerHTML. You can simplify your code down to this:
$('.lang-in-serach-blg').each(function() {
this.innerHTML = this.innerHTML.replaceAll('English', '<img src="https://placekitten.com/50/50">');
});
$('.lang-in-serach-blg').each(function() {
this.innerHTML = this.innerHTML.replaceAll('Francais', '<img src="https://placekitten.com/60/60">');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="lang-in-serach-blg">
English filler text filler text English.
</p>
<p class="lang-in-serach-blg">
English filler text filler text English.
</p>
<p class="lang-in-serach-blg">
Francais filler text filler text Francais.
</p>
If you're changing the content of the webpage after the DOM loads, then you should run this code again after the DOM is changed. If you were to use a framework that handles state for you (ie: React, Vue, Svelte, etc.), then the framework would handle this for you, but with pure jQuery you'll need to do it yourself.
2 Comments
jQuery(document).ready, then again when you update the page.