1

I have some code like this:

<p>Nuno</p>
<p>Eimes</p>

How can I manipulate it like this:

<p><a href="name/Nuno">Nuno</a></p>
<p><a href="name/Eimes">Eimes</a></p>

I've tried:

var name=$(this).text();
$( "p" ).each(function() {
  $(this).prepend('<a href="id/'+ $(this).text() +'"> ');
$(this).append("</a>");
});

but it results:

<p><a href="id/Nuno"> </a>Nuno</p>
<p><a href="id/Eimes"> </a>Eimes</p>

the <a> is not inside $('p').text(); also if i change to name. it didn't show the value.

1
  • What's this in var name=$(this).text();? What's the scope? Commented Sep 14, 2013 at 5:07

5 Answers 5

2
$( "p" ).each(function() {
   var text = $(this).text();
   $(this).wrapInner('<a href="name/'+text+'"></a>');
 });

Live Demo

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

2 Comments

@MattBall what do you mean..?
@DipeshParmar nobody knows you are going to edit it... so when a person sees an answer they judge by what they see at that time...
0

Simple and .wrapInner()

$('p').wrapInner(function(){
    return '<a href="name/' + $(this).text() + '" />' // even this.innerHTML instead of $(this).text() will do
})

Demo: Fiddle

Comments

0

Once you've extracted the name, I would just rewrite the whole code within the <p></p> tags again:

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

Comments

0

You just need to grab the inner stuff, then replace everything in the tag with the new HTML:

var name=$(this).text();
$( "p" ).each(function() {
    old = $(this).html();
    $(this).html('<a href="id/'+ old +'">'+old+'</a>');
});

Fiddle

Comments

0

Demo

$('p').html(function () {
    return '<a href="name/' + this.innerHTML + '">' + this.innerHTML + '</a>';
});

.html()

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.