1

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.

Michael M.
11.2k11 gold badges22 silver badges46 bronze badges
asked Nov 4, 2022 at 21:57
0

1 Answer 1

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.

answered Nov 4, 2022 at 22:07
Sign up to request clarification or add additional context in comments.

2 Comments

I use this code in a site that has several pages and pages 2, 3, etc. are loaded in Ajax. This code works fine when I open the site (first page), but when I load subsequent pages (in Ajax), the code stops working. Do I need to change anything? I start my code with: jQuery(document).ready(function( $ ){
@Pudy If you're dynamically changing the page's content, then you should run the code in my answer again. A simple way to do this would be to put all the code from my answer in a function. You can then call this function inside jQuery(document).ready, then again when you update the page.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.