views:

129

answers:

4

I have a several links whose text content I'd like to replace with a automatically generated image based on the text content.

So currently it looks like this:

<a href="blabla" class="mLink">
<span class="mText">The Text in Question</span>
</a>

and I would like to have either

<a href="blabla" class="mLink">
<img src="/ImageTextHandler.ashx?message=The+Text+in+Question" alt="The Text in Question"/>
</a>

or

<a href="blabla" class="mLink">
<span class="mText">
    <img src="/ImageTextHandler.ashx?message=The+Text+in+Question" alt="The Text in Question"/>
</span>
</a>

How do I access the element in question inside a .replaceWith or .html so that I can get the text content?

+2  A: 

try this

$(".mLink").each(function (i) {

   var thisText = $(this).find(".mText").text();
   $(this).html("<img src='/ImageTextHandler.ashx?
         message=" + thisText + "' alt='" + thisText + "'/>");

});
Josh
+1  A: 

Using localized selectors

$(".mLink").each(function() {
    var text = $("span", this).text();
    $("span", this).replaceWith("<img src='/ImageTextHandler.ashx?message="+
                                  text+"' alt='"+text+"' />");
});
peirix
+1  A: 
$(function() {    
    var mySpan = $('a.mLink span.mText');
    var text = mySpan.text();
    var link = text.split(' ').join('+');

    mySpan.replaceWith($("<img src='/ImageTextHandler.ashx?message=" + link + "' alt='" + text + "'/>"));
});

Working Demo here

Code from demo

$(function() {

    $('#button').click(function() {

      $('a.mLink span.mText').each(function() {    
        var text = $(this).text();
        var link = text.split(' ').join('+');
        $(this).replaceWith($("<img src='/ImageTextHandler.ashx?message=" + link + "' alt='" + text + "'/>"));
      });

    });
});
Russ Cam
nice conversion to link format. But will this work for several links? Won't they all end up the same?
peirix
Not if you perform the operation on each matched element as in the example :)
Russ Cam
A: 

Try something like this...

$(".mText").each(function(){
  var url = "/ImageTextHandler.ashx?message=" + escape($(this).text());
  var image = $("<img>");
  image.attr("src") = url;
  image.attr("alt") = $(this).text();
  $(this).text("");
  $(this).append(image);
});
belugabob
you've mismatched your quotes should be $("<img>");
Josh
Curse those fat fingers :-)Thanks for that - I've corrected the error.
belugabob