简体   繁体   中英

find and replace a unique html (href) string using javascript

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>

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;
});

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')); 
});

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; 
        }
    }
}

Just do this :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM