1

Using Javascript, how can I change this classless anchor (assuming targeting unique href string):

<a href="/unique-url-string/"></a>

to this, on page load:

<a href="/replacement-url-string/"></a>

5 Answers 5

4

You can select the element based on its href prop.

$('a[href="/unique-url-string/"]').prop('href', '/replacement-url-string/');

If you want to only search the pathname of these urls and keep the domain name the same you can try something like:

$('a').filter(function() {
  return this.pathname === "/foo/bar"
}).prop('href', function () {
  this.pathname = '/butt/butt/butt';
  return this;
});
Sign up to request clarification or add additional context in comments.

2 Comments

fantastic! did it. out of curiosity, would it be as easy to replace say only a portion of the href string? for example: domain.com/unique-string/ to domain.com/replacement-url-string/ but ignoring the domain.com portion?
You'd have to keep track of what the domain is since you'd be rewriting the whole thing. I'll post a small update to my answer.
2

Using only JavaScript without library

function replaceLink(oldLink, newLink) {
var x = document.getElementsByTagName("a");
    for(var i = 0; i < x.length; i++)
        if(x[i].href == oldLink) {
            x[i].href == newLink; 
            break; 
        }
    }
}

Comments

1

Try this:

$(function(){
   $('a[href="/unique-url-string/"]').attr('href', '/replacement-url-string/'); 
});

To replace a portion:

$(function(){
    var a = $('a[href="/unique-url-string/"]');
   a.attr('href', a.attr('href').replace('unique', 'replacement')); 
});

Comments

0

var link = document.getElementById('linkToChange');
console.log(link.href);
link.href = "http://www.google.com";
<a href="about:blank" id="linkToChange">me</a>

Comments

0

Just do this :

$().ready(function(){
    $('a').attr("href").replace("unique","replacement");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.