Turn text into link with 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 this from <span>to <a>and add hrefwith my link?

+5
source share
2 answers

Description

You can use jQuery method replaceWith().

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

Example

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

Additional Information

+12
source

You can try jQuery replaceWith()using the syntax of the callback function to extract the current contents of the span element and place it in a new anchor element.

() , :

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

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

: http://jsfiddle.net/cSZGr/1/

(. , , "span", , , - , .)

, , :

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

:

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

:

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

P.S. .wrap(), span, , , , - .

+5

All Articles