Kay
Kay

Reputation: 71

How to replace href with value of data-href?

I have got html as below

<a href="" data-href="/somefile.php?id=10&refcode=/test.php">Hello</a>

and I need to replace href with the value in data-href so that the above becomes something like

<a href="/somefile.php?id=10&refcode=/test.php">Hello</a>

//the following doesnt work .. 

$(function() {
 $('a[data-href]').attr('href', $(this).attr('data-href'));
});

Any suggestions? Basically I want to hide some links for some reason from search engines/bots etc. so I am happy if I can get the above working or if you can suggest any better idea to achieve the same? Thanks.

Upvotes: 2

Views: 18338

Answers (1)

Pekka
Pekka

Reputation: 449505

$(this) does not refer to the a element in this case.

Try

$('a[data-href]').each(function() { 
 $(this).attr('href', $(this).attr('data-href'));
});

using each(function() {}) will bind the this keyword to the a element inside the function.

Upvotes: 9

Related Questions