Home > front end >  Get and replace string using Javascript
Get and replace string using Javascript

Time:09-02

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

CodePudding user response:

Use querySelectorAll

$(function() {
  document.querySelectorAll("a[target=_top]").forEach(function(elem) {
    this.target="_blank";
  });
  });
});

CodePudding user response:

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>

  • Related