views:

20

answers:

1

Hello, I am trying to turn specific words or phrases into links with jQuery. So far I have only been successful in changing a span with a class="link" to an anchor tag after a hover event. My problem is that I want them to change when the page loads. As an added benefit it would be nice to target any words or phrases without having to put them in spans.

$('span.link').hover(function () {

    $(this).replaceWith("<a href='http://mydomain.com'&gt;" + $(this).text() + "</a>");

});

Works only when they hover over the text, but what I really want is something like this:

var keyword = 'my keyword';

var link = $(document).find(keyword);

$(document).ready(function() {
    link.replaceWith("<a href='http://mydomain.com'&gt;" + $(this).text() + "</a>");
 });
+2  A: 

Instead of using the hover event to initiate the change, use the each method which will execute for each matched element the moment you call it ..

so

$('span.link').each(function () {

    $(this).replaceWith("<a href='http://mydomain.com'&gt;" + $(this).text() + "</a>");

});

will convert all yours spans to links in one go ..

Gaby
Thank you, now I understand .each(). I appreciate this!
Montana Flynn