Marksyw Marksyw - 2 months ago 6
Javascript Question

Replace multiple links

I'm trying to replace multiple links but only the first one is replaced,
all the other remain the same.

function rep(){ var text = document.querySelector(".link").querySelector("a").href;

var newText = text.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');

document.querySelector(".link").querySelector("a").href = newText; }


any suggestion

Its multiple a href links inside class .link

Answer

Your mistake is in using querySelector, so document.querySelector(".link").querySelector("a") literally translates to: get me the first a inside the first .link;

Use querySelectorAll; and you can combine the two selectors:

Vanilla JS:

[].forEach.call(document.querySelectorAll('.link a'), function(a){
    a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});

Or, since you'll select items more often, a little utility:

function $$(selector, ctx){
    return Array.from((ctx && typeof ctx === "object" ? ctx: document).querySelectorAll(selector));
}

$$('.link a').forEach(function(a){
    a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
})

Or in jQuery:

$('.link a').each(function(){
    this.href = this.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});