1

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>

6 Answers 6

3

.wrapInner() wraps element around passed value.

Try this:

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

Fiddle here.

Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

1

You can do this way:

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

Demo Fiddle

Comments

1

try something like this

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

Comments

1

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

1 Comment

Can tell me the reason to down it..??
0

Heres the FIDDLE

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.