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?
You can use jQuery's replaceWith()
method.
replaceWith() Replace each element in the set of matched elements with the provided new content.
$("span").replaceWith('<a href="link">link text</a>');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With