Question

I am trying to replace the first 5 letters in all links on that page that contain #OFN# in the first 5 letters of the link with an image to replace #OFN# text, but want to retain the rest of the link text.

Here's what I'm using so far...

$(document).ready(function() {
    $("a:contains('#OFN#')").each(function() {
        var calSubject = $(this).text().substring(5);
        $(this).replaceWith("<img src='/images/ofn_bullet.gif' width='10' height='10' style='width: 10px; height: 10px; border: none;' />" + calSubject);
    });
});

But this approach removes the <a> tag completely from the text. How can I do this without removing the <a> tags

Here's an example HTML of the link:

<a href="#" onclick="eventDisplay('980','4/18/2013')">#OFN# 2013 Midwest Regional Meeting</a>

I tried using .children() but that doesn't seem to work either. What am I doing wrong here?

Was it helpful?

Solution

Select the text nodes and update them instead. jsFiddle Demo

$(document).ready(function() {
    $("a:contains('#OFN#')").contents().each(function(){
        // skip if not a text node
        if (this.nodeType != 3) {
            return true;
        }
        this.nodeValue = this.nodeValue.substr(5);
        $(this).before("<img src='/images/ofn_bullet.gif' width='10' height='10' style='width: 10px; height: 10px; border: none;' />");
    });
});

OTHER TIPS

use html instead of replaceWith. Check out this fiddle:

http://jsfiddle.net/lbstr/MPTp7/

replaceWith will replace the element that it is invoked on, which explains the behavior that you described. By using $.fn.html, you are replacing everything inside of the anchor tag.

Use the html method to put the code inside the link instead of replacing it:

$(this).html("<img src='/images/ofn_bullet.gif' width='10' height='10' style='width: 10px; height: 10px; border: none;' />" + calSubject);

I would do something slightly more verbose:

var regex = /^#0FN#/;
$("a").each(function() {
    var $this = $(this), html = $this.html();
    if (regex.test(html)) {
        html.replace(/#0FN#/, "image stuff");
        $this.html(html);
    }
});

This looks clearer to me :

<a href="#" class="ofn" onclick="eventDisplay('980','4/18/2013')">
    <span>2013 Midwest Regional Meeting</span>
</a>

And

$(document).ready(function() {
    $('a.ofn').prepend('<img class="icon" src="/images/ofn_bullet.gif" />');
});

And

a.ofn .icon {
   width: 10px;
   height: 10px;
   border: none; /* Actually i think you mean outline rather than border */
}

Unless you MUST do it the way you do it for some reasons you didn't ell us about.

You could also move the onlick from the a tag to the javascript if the parameters of eventDisplay are always the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top