ben
ben

Reputation: 41

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?

Upvotes: 4

Views: 11858

Answers (3)

ricick
ricick

Reputation: 5786

I'd reccomend JQIR for this. first replace "basketball" with "<span class="jqir">basketball</span>" as you are doing above. Then run the following:

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

This assumes that you have an image images/basketball.png. You can adjust as needed.

Upvotes: 0

SLaks
SLaks

Reputation: 888293

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 ... />'); });

Upvotes: 2

Vivin Paliath
Vivin Paliath

Reputation: 95598

("*").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.

Upvotes: 7

Related Questions