skip to Main Content

My website have lot of links and i am trying to replace all a href target _top to _blank. How can i do this with javascript?

It will find all _top in my web page and replace with _blank

I am trying like this :

// const string = document.getElementsByTagName('a')[0].innerHTML
const string = document.querySelector("_top"); //getting string
var newstring = string.replace(/_top/, '_blank'); //trying to replace string in whole page
const myTimeout = setTimeout(selecteAd, 2000); //set timeout so webpage get loaded full
<!-- example string -->
<a data-asoch-targets="imageClk" href="https://www.eample.com" target="_top" x-ns-8l6in-e="2"><canvas class="ns-8l6in-e-3 image" x-ns-8l6in-e="3" width="600" height="314"></canvas></a>

Updated :

Data is coming from Google adsense async code. (Got similar solution in other part of Stackoverflow but still i am unsuccessful in replacing How to get DIV sub-elements using javascript )

2

Answers


  1. Chosen as BEST ANSWER

    Credit to original answers who deleted the answer :

    document.querySelectorAll('a[target="_top"]').forEach(el => el.target = '_blank');
    <a href="https://www.example.com" target="_top">foo</a><br />
    <a href="https://www.example.com" target="_top">bar</a>


  2. Use querySelectorAll

    $(function() {
      document.querySelectorAll("a[target=_top]").forEach(function(elem) {
        this.target="_blank";
      });
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search