Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery replace text with image, help

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

i'm only able to change the text to another string of text, but how can I pass an image?

like image 476
ben Avatar asked Oct 22 '25 14:10

ben


2 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 wanted to replace the entire element. Check out my updated answer.

like image 104
Vivin Paliath Avatar answered Oct 24 '25 04:10

Vivin Paliath


You need to modify the html() rather than the text().

You can simplify your code to

$("*").filter(function() { return !$(this).children().length; })
      .html(function(index, old) { return old.replace('basketball', '<img ... />'); });
like image 28
SLaks Avatar answered Oct 24 '25 04:10

SLaks