Javascript - How to add to all href="" of a div a domain "http://site.com"

Asked

Viewed 59 times

1

I’m with a system that seeks product suggestions via ajax. He pulls the information, but this information comes from an external site, and he has the local URL. href="/produto/123, need to get it inserted in all href="", the domain of the site. Ex: href="http:/meusite.com/produto/123. For a better explanation, I need all the href="" contained within:

<div class="recommendation-shelf"></div>

Be aggregated http://meusite.com inside href="<urldomeusite>/produto/123" being like this:

href="http://meusite.com/producto/123"

Note: If possible, in Pure Javascript...

2 answers

5


There is a new way to do this. It was added to HTML 5 and is base.

The base tells the browser that all non-absolute urls start at that url. You can only have 1 per page, others will be ignored.

An example would be like this:

<base href="http://answall.com">
<a href="/questions/tagged/javascript+html">Tag JavaScript</a>

If there are different sites and need to change only in some elements you can do so:

var site = 'http://meusite.com';
var ancoras = document.querySelectorAll('.recommendation-shelf a');
[].forEach.call(ancoras, function(a) {
    var href = a.getAttribute('href').split('/').filter(Boolean);
    a.href = [site].concat(href).join('/');
    
    // isto é só para o exemplo
    a.innerHTML = a.href;
});
a {display: block;}
<a href="/questions/tagged/javascript+html">Tag JavaScript</a>
<div class="recommendation-shelf">
    <a href="questions/tagged/javascript">Tag JavaScript</a>
    <a href="/questions/tagged/html">Tag HTML</a>
</div>

1

I am using jquery

#I edited

$(document).ready(function(){
  $(".recommendation-shelf").change(function() {
    $('.recommendation-shelf').find('a').each(function(i, obj) {
        var href = $(obj).attr('href');
        $(obj).attr('href', 'http://meusite.com/'+href)
    });
  })
})
  • I want something simple, using Javascript Pure.

  • I can assure you that the simplest way is to use Jquery rather than pure javascript. There was an error in my script and I’ve updated it

  • 1

    @Brenoperucchi I respect your opinion but I deeply disagree that the simplest way is to use jQuery, that is, it is your right to have your opinion, but it is only an opinion. I just want to make it clear to anyone who reads here that doesn’t think this is an absolute truth.

  • @bigown to my reality is rather more complicated pure javascript than jquery. I understand the difference of opinion, but each has its own. I don’t want to argue because I really understand what you meant. I will effect a change in the comment if I could.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.