Reputation: 1368
My goal is to change text in span .name into element with link-
<div class="input-wrap">
<span class="name">favorite 1</span>
</div>
How can I use JS to add link to this element so as it looks like that:
<div class="input-wrap">
<span class="name"><a href="/specyficwebsite.html">favourite 1</a></span>
</div>
Upvotes: 1
Views: 97
Reputation: 2012
Heres the FIDDLE
var $name = $(".name");
var txt = $name.text();
$name.html('<a href="/specyficwebsite.html">' + txt + '</a>');
Upvotes: 0
Reputation: 28763
Try with .wrapInner()
like
$(".name").wrapInner( '<a href="/specyficwebsite.html"></a>' );
See this FIDDLE You can also try like
var txt = $('.name').text();
$('.name').html('<a href="/specyficwebsite.html">' + txt + '</a>');
Or directly
$('.name').html('<a href="/specyficwebsite.html">' + $('.name').text() + '</a>');
Try this FIDDLE
Upvotes: 1
Reputation: 10906
try something like this
$(function(){
var link = '<a href="/specyficwebsite.html">'+$('.name').text()+'</a>';
$('.name').html(link);
})
Upvotes: 1
Reputation: 15709
.wrapInner()
wraps element around passed value.
Try this:
$(".name").wrapInner("<a href='/specyficwebsite.html'></a>");
Upvotes: 3
Reputation: 1700
You can do this way:
$(".name").html(function(){
$(this).wrap("<a href='/specyficwebsite.html'></a>")
})
Demo Fiddle
Upvotes: 1
Reputation: 135862
You could:
$('span.name').html(function () {
return $('<a>').attr('href', '/specyficwebsite.html').text($(this).text());
});
See demo jsFiddle here.
Generated HTML:
<span class="name"><a href="/specyficwebsite.html">favourite 1</a></span>
Upvotes: 2