1

I am trying get all HTML links in a website's body section within a string and replace them to another link.

Tried something like this but did not work:

var search = "https://www.cloudflare.com/5xx-error-landing?utm_source=error_footer";
var replacement = "https://example.com/";

document.body.innerHTML = document.body.innerHTML.split(search).join(replacement)

Where "https://www.cloudflare.com/5xx-error-landing?utm_source=error_footer" is the link I want to replace and "https://example.com/" is the link that I want to replace with.

1
  • Is it only that one specific link you want to change within the entire page? Commented Jul 10, 2017 at 7:54

4 Answers 4

5

How about this:

$("[href='your link']").attr("href","new link");
Sign up to request clarification or add additional context in comments.

7 Comments

the question is about only JavaScript I guess
@KoushikChatterjee sorry but tagged by jquery
Edited and reduced the ==, now just using a css selector
any getter will return you the value of first element, but any setter will set it to all the elements that matches the selector, because you are doing against that. just try it out :)
@NirTzezana thanks for the edit, its a more optimized answer now. Looks good :) thums up ^
|
0

Here is a solution with plain javascript as per your question

document.querySelectorAll("[href='" + search + "']").forEach(function(el){
    el.href = replacement );
});

If you want to use jQuery, as you tagged, follow the answer of Nir Tzezana

Comments

0
$('body').find('a').each(function(){
    $(this).attr('href','your_new_link');
});

or for different href:

$('body').find('a').each(function(){
    var ahref = $(this).attr('href');
    if ( ahref == 'your_old_link') {  /// or ahref.indexOf("your_old_link") >= 0
         $(this).attr('href','your_new_link_1');
    }else{
         $(this).attr('href','your_new_link_2');
    }

});

2 Comments

its not correct because ahref is string .. you can not call .attr because is not jquery Object ... you tried yourself?
yes now its correct. $(this) is good but for replace and nested is it hell, I like using store that into variable like this jsfiddle.net/rqxdLp88
0

Just use

  $("body a[href='https://www.cloudflare.com']").attr("href","https://example.com/");

3 Comments

this is bad because replace ALL links but OP wants to replace only specific links
is .each is required here?
any getter will return you the value of first element, but any setter will set it to all the elements that matches the selector, because you are doing against that. just try it out :

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.