views:

1398

answers:

4

I have a template that gets screenscraped from an outside vendor and need to include absolute paths in the navigation so the externally hosted content will properly link back to our site.

Right now the page/template is driven by a global menu app written by our back end development staff... so anyone who updates our site goes in and changes the menus and their paths...

Right now all of the links are linking to relative paths back to the root.

For example

<a href="/">Home</a>
<a href="/news/">News</a>
<a href="/media/">Media</a>
<a href="/other/">Other</a>

I need a simple way (preferably with jquery) to prepend "http://www.domain.com" to each of those links.

A: 

I don't recommend using javascript to solve this issue. This should be solved in the page template. However, if you still want a jquery solution then here you go. Assuming those links have a specific class that distinguish them from internal links:

$('a.external').each(function() {
    $(this).attr('href', domain_name + $(this).attr('href'));
})
Nadia Alramli
+3  A: 
$('a').attr('href', 'http://www.domain.com'+$(this).attr('href'));
Marwan Aouida
Does this work in IE? I thought IE normalised the href internally before you could access it?
SpoonMeiser
Ignore that comment. I'm wrong.
SpoonMeiser
+1  A: 

Please note that jQuery object $("a").attr("href") is not equal to $("a").get(0).href ?

$("a").each(function() {
   alert(this.href);
   $(this).attr("href") = this.href;
});

In you case, this may not help you , because you want static markup, javascript generate dynamic content. But it seems that you want static markup in that case it has to be emit by server.

Fred Yang
You should sort out your code snippet.
SpoonMeiser
+1  A: 

you don't need jquery for such a simple function....

var elements = document.getElementsByTagName("a");
var eachLink;
for (eachLink in elements) {
 var relativeLink = eachLink.href;
 var absoluetLink = ["http://",domainName,"relativeLink"];
 eachLink.href = absoluteLink.join("");
}

something like this should work, and it runs much faster and you won't need to load the entire jquery library just to run 6 lines of code :P

Jlam