Jquery replace text with image help

("*").each(function () { 
   if ($(this).children().length == 0) {
       $(this).text($(this).text().replace('basketball','test')); 
   } 
});

I can only change the text to another line of text, but how can I transfer the image?

+3
source share
3 answers
("*").each(function () { 
   if ($(this).children().length == 0) {
      var newHTML = $(this).html().replace('basketball','<img src = "image.jpg" />');
      $(this).html(newHTML);
   } 
});

EDIT

My mistake. I thought you want to replace the whole element. Check out my updated answer.

+6
source

You need to change html(), not text().

You can simplify your code to

$("*").filter(function() { return !$(this).children().length; })
      .html(function(index, old) { return old.replace('basketball', '<img ... />'); });
+2
source

I would recommend JQIR for this. first replace "basketball"with "<span class="jqir">basketball</span>"as you did above. Then run the following:

$(".jqir").jQIR("png", "images/");

This assumes you have /basketball.png images. You can customize as needed.

0
source

All Articles