Home > Software engineering >  Change a tag's href
Change a tag's href

Time:10-23

I'm making an userscript for enter image description here

I already found how to select it:

var x = document.querySelector(".oJZym").getElementsByTagName("a");
x[0]

I want it to open a new tab to https://instagram.com/nukl3ar_p/ . I've already tried:

var x = document.querySelector(".oJZym").getElementsByTagName("a");
x[0].href = "https://instagram.com";

or

var x = document.querySelector(".oJZym").getElementsByTagName("a");
x[0].onclick = window.open("https://instagram.com/nukl3ar_p/", "_blank");

But it keeps redirecting me without even having clicked it. How to fix?

CodePudding user response:

Try this, use CSS Selector > to get the child <a> then set href.

var x = document.querySelector(".oJZym>a");
x.href = "https://instagram.com/nukl3ar_p/";
x.target ='_blank';
<div  class="oJZym" ><a href="/">Test</a></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

 var x = document.querySelector("oJZym a")
 x[0].href = "https://instagram.com";

CodePudding user response:

You can use the d3 library to modify it like this:

<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
<script>

const div = d3.select(".oJZym").select("a")
              .attr("href","https://instagram.com/nukl3ar_p/")
              .attr("target","_blank");

</script>

This script will use the d3 library to select the hyperlink within the ".oJZym" class and set its href and target attribute.

CodePudding user response:

Try these line..

var x = document.querySelector("oJZym   a")
x[0].href = "https://instagram.com";

CodePudding user response:

Because when the page gets hoisted, your code gets executed. so they are redirecting here. You need to use preventDefault to stop that.

x[0].onclick = function(event){
      event.preventDefault()
      window.open("https://instagram.com/nukl3ar_p/", "_blank");
}
  • Related