Question

I'm reading 'JavaScript Missing Manual' and there is this script that automatically adds URL of a link next to this link itself.

$('a[href^="http://"]').each(function(){
    var href = $(this).attr('href');
    href = href.replace('http://', '');
    $['a'].after(' (' + href + ') ');
}); // end each

The problem is that it doesn't work at all. Could someone please explain me what's wrong with this code?

Was it helpful?

Solution

Change this line

$['a'].after(' (' + href + ') ');

to

$('a').after(' (' + href + ') ');

$ should be called as a function, not an array.

Although looking at your code, you probably want this instead:

$(this).after(' (' + href + ') ');

edit:

here is the full code:

$('a[href^="http://"]').each(function(){
var href = $(this).attr('href');
href = href.replace('http://', '');
$(this).after(' (' + href + ') ');
}); // end each

OTHER TIPS

May I suggest a similar, but shorter, version?

$('a[href^="http://"]').each(function(){
    $(this).after(" ("+$(this).attr('href').replace("http://",'')+")");
}); // end each

Pretty much fmsf's solution + a small modification to make the code a bit shorter. o/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top