Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn text into a link with jquery

Tags:

html

jquery

if I had a span element with some text:

<span>I want this to be a link</span>

is there a way to use jquery to turn that from <span> to <a> and add an href with my link?

like image 503
Anthony Miller Avatar asked Jan 06 '12 22:01

Anthony Miller


2 Answers

Description

You can use jQuery's replaceWith() method.

replaceWith() Replace each element in the set of matched elements with the provided new content.

Sample

$("span").replaceWith('<a href="link">link text</a>');

More Information

  • jQuery.replaceWith()
like image 74
dknaack Avatar answered Oct 08 '22 16:10

dknaack


You could try jQuery's replaceWith() using it's callback function syntax to extract the current content of the span element and put it in the new anchor element.

Put in a (slightly) generic function it would look something like this:

function replaceWithAnchor(selector,url) {
   $(selector).replaceWith(function() {
     return $("<a></a>").attr("href",url).append($(this).contents());
   });
}

replaceWithAnchor("span", "http://google.com");

Here's a working demo: http://jsfiddle.net/cSZGr/1/

(Note: you'll presumably want a more specific selector than just "span" or it will replace all spans as shown in my demo - although you'll note the individual span content is retained in the resulting anchor elements.)

Of course if you don't need a generic version then just do this:

$("span").replaceWith(function() {
  return $("<a></a>").attr("href","http://URL.com").append($(this).contents());
});

Before:

<span>I want this to be a link</span>

After:

<a href="http://google.com">I want this to be a link</a>

P.S. Another way to do it is with the .wrap() method, which wouldn't actually replace the span, it would add an anchor element around the span. This might be helpful if your span has styles that you don't want to lose or something.

like image 35
nnnnnn Avatar answered Oct 08 '22 16:10

nnnnnn