0

I'm working on a site where the content is being scraped from another site (both owned by same person). When it pulls in links, the href isn't formatted the way I need it to be, so I'm trying to preserve the original value and just add a slash to the beginning of it. I've gotten close, but can't get it to work properly. The current format is href="like-this", but I need it to be href="/like-this".

This what I've tried that came close:

$('.disamb li a').attr('href', function() {
    return '/' + this.href;
});

That returns the whole absolute url with a / at the very beginning. So I tried using each():

$('.disamb li a').each(function() {
    $(this).attr('href', '/'+this.href);
});

Same result. I tried a couple of other ways, but these two were the closest. How can I go about doing this without then running it through a replace function to strip it down to what I need? (that just seems sloppy)

admdrew
  • 3,790
  • 4
  • 27
  • 39
stinkysGTI
  • 573
  • 6
  • 21

1 Answers1

1

Try this:

$('.disamb li a').attr('href', function(i, old) {
    return '/' + old;
});

The function receives two arguments, the index of the current element, and the current value of the attribute.

When you use this.href, you're getting the URL after the browser has canonicalized to a full, absolute URL, not the string value of the attribute.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Ah ok, that's good to know about using `this`. This worked exactly how I needed it to. Thank you! I knew I was close, but was going about it wrong. – stinkysGTI Dec 10 '14 at 22:45