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

1
  

I have a system that looks for product suggestions via ajax. It pulls the information, however this information comes from an external site, and it has the local URL. href="#"># , I need to have it inserted in all href="" , the domain of the site. Ex: href="#">#

asked by anonymous 12.08.2016 / 05:29

2 answers

5

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

base tells the browser that all urls that are not absolute begin in this url. You can only have 1 per page, the others will be ignored.

An example would look like this:

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

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

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>
    
12.08.2016 / 08:15
1

I'm using jquery

#Edite

$(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)
    });
  })
})
    
12.08.2016 / 07:15