user1411607
user1411607

Reputation:

Replace text of link with link href value in jquery

I want to replace text of a link with link href value.

I have 1000 links in table like this.

html

<td  valign="middle"class="link2"align="left" width="auto" >
<a href="http://www.example1.com" target="_blank">Item1</a>
</td>
<td  valign="middle"class="link2"align="left" width="auto" >
<a href="http://www.example2.com" target="_blank">Item2</a>
</td>
.
.
.
.

I want to replace text value Item1 Item2 ... with link href value http://www.example1.com http://www.example1.com ...

I am trying this way but its not working.

jquery

$('.link2 a').html($(this).attr('href'));
//also tried like this.
$('.link2 a').html(this.attr('href'));

$('.link2 a').text($(this).attr('href'));
//also tried like this.
$('.link2 a').text(this.attr('href'));

Please suggest way to do this.

Thanks.

Upvotes: 1

Views: 997

Answers (7)

Anto king
Anto king

Reputation: 1222

Easy use below code

    $('.link2 a').each(function(){
   $(this).text($(this).attr('href'));
 });

Upvotes: 0

Adil
Adil

Reputation: 148110

Use callback function of html(), i.e. .html( function ) or .text( function )

Live Demo

$('.link2 a').html(function(){
   return this.href;
});

Upvotes: 3

Ishan Jain
Ishan Jain

Reputation: 8161

Try this:

$('.link2 a').each(function(){
  $(this).text($(this).attr('href'));
});

Upvotes: 0

dhalfageme
dhalfageme

Reputation: 1545

Try this:

$('.link2').each(
 function(index)
 {
   $(this).children(":first").text($(this).attr('href'));
 }


);

Upvotes: 0

Saksham
Saksham

Reputation: 9380

Use this

$('.link2 a').each(function(){
  $(this).html($(this).attr('href'));
});

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this: You need to iterate each anchor tag as you need to read each anchor tag href value and set it as its text.

$('.link2 a').each(function(){
  $(this).text($(this).attr('href'));
});

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

Here this is not refering to anchor. Loop through each anchor node and set its text. Try with this code

 $('.link2 a').each(function(){
   $(this).text($(this).attr('href'));
 });

Upvotes: 1

Related Questions