Home > OS >  Change text with image in jquery
Change text with image in jquery

Time:11-05

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?

CodePudding user response:

You can simplify your code down to this:

$('.lang-in-serach-blg').each(function() {
  this.innerHTML = this.textContent.replaceAll('English', '<img src="https://placekitten.com/50/50">');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p >
  English filler text filler text English.
</p>

<p >
  English filler text filler text English.
</p>

CodePudding user response:

thank you so much.

There's just one problem:

I have the names of several countries that I want to replace with flags, but only the last code is executed and the first countries do not load the image list.

jQuery('.lang-in-serach-blg').each(function() {
    this.innerHTML = this.textContent.replaceAll('English', '<img src="flags/24/en.png">');
});

jQuery('.lang-in-serach-blg').each(function() {
  this.innerHTML = this.textContent.replaceAll('Francais', '<img src="flags/24/fr.png">');
});

With this code, only the French flag will be loaded and no image will be seen instead of the English text.

  • Related