2

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'>" + $(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'>" + $(this).text() + "</a>");
 });
Montana Flynn
  • 299
  • 1
  • 4
  • 10

1 Answers1

2

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'>" + $(this).text() + "</a>");

});

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

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317