-1

Like a link is coming dynamically in a <code><div></code>, Can I change domain name of all the hyperlinks.

For example:-

This is hyperlink link tag

<a href="http://onedomain.com/offers/testing-something/">.

Can I change this to

<a href="http://seconddomain.com/offers/testing-something/">

dynamically with jquery. All other parameters in link should be same but on domain name should be changed. If it is possible then please explain how, I will be grateful to you.

Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85

3 Answers3

1

Use replace():-

$(document).ready(function(){
   $('a').each(function(){
        this.href = this.href.replace('onedomain.com', 'seconddomain.com');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://onedomain.com/offers/testing-something/">link</a>

@satpal solution will also work:-

$(document).ready(function() {
  $('a').attr('href', function(_, value) {
    return value.replace('onedomain.com', 'seconddomain.com');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://onedomain.com/offers/testing-something/">link</a>
StudioTime
  • 18,874
  • 30
  • 103
  • 186
Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
  • 1
    You can aslo suggest `$('a').attr('href', function(_, value){ return value.replace('onedomain.com', 'seconddomain.com'); });` – Satpal Feb 27 '17 at 12:09
0

You can simply change the host property of the <a> elements using prop( propertyName, function )

$('a').prop('host',function(){
  return 'seconddomain.com';
})

// for demo loop over elements and log adjusted href
.each(function(){
  console.log(this.href)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://onedomain.com/offers/testing-something/">
<a href="http://onedomain.com/offers/something-else/">
charlietfl
  • 164,229
  • 13
  • 110
  • 143
-1

Just do:

$('a').each(function(){
  $(this).attr('href').replace("OLD-DOMAIN","NEW-DOMAIN");
});
Roy Bogado
  • 4,108
  • 1
  • 12
  • 29