Reputation: 385
I'm trying to convert all fragment links to relative ones by removing the leading #
, but the following will not run:
$('a[href^=#]').attr('href', $(this).attr('href').substring(1));
If I replace $(this).attr('href').substring(1)
with $(this).attr('href')+'test'
or 'test'+'TEST'.substring(1)
it runs. What's wrong with $(this).attr('href').substring(1)
?
Upvotes: 0
Views: 221
Reputation: 78525
Your $(this)
does not refer to the <a>
tag found by your selector, rather the current scope of the code. You need to use the function overload of attr instead:
$('a[href^=#]').attr('href', function(i, attr) {
return attr.substring(1);
});
Upvotes: 4