lipenco
lipenco

Reputation: 1368

Changing text to link with javascript

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

Answers (6)

Vond Ritz
Vond Ritz

Reputation: 2012

Heres the FIDDLE

var $name = $(".name");
var txt = $name.text();
$name.html('<a href="/specyficwebsite.html">' + txt + '</a>');

Upvotes: 0

GautamD31
GautamD31

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

rajesh kakawat
rajesh kakawat

Reputation: 10906

try something like this

        $(function(){
            var link = '<a href="/specyficwebsite.html">'+$('.name').text()+'</a>';
            $('.name').html(link);
        })

Upvotes: 1

codingrose
codingrose

Reputation: 15709

.wrapInner() wraps element around passed value.

Try this:

$(".name").wrapInner("<a href='/specyficwebsite.html'></a>");

Fiddle here.

Upvotes: 3

Greenhorn
Greenhorn

Reputation: 1700

You can do this way:

$(".name").html(function(){
$(this).wrap("<a href='/specyficwebsite.html'></a>")
})

Demo Fiddle

Upvotes: 1

acdcjunior
acdcjunior

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

Related Questions