简体   繁体   English

更改标签的 href

[英]Change a tag's href

I'm making an userscript for Instagram .我正在为Instagram制作用户脚本。 What I want to do is to change an <a> tag's href.我想要做的是更改<a>标签的 href。 This tag doesn't have any ID/class.此标签没有任何 ID/类别。 在此处输入图片说明

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/ .我希望它打开一个新标签到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?怎么修?

Try this, use CSS Selector > to get the child <a> then set href.试试这个,使用 CSS Selector >来获取孩子<a>然后设置 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>

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

You can use the d3 library to modify it like this:您可以使用 d3 库像这样修改它:

<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.此脚本将使用 d3 库选择“.oJZym”类中的超链接并设置其 href 和 target 属性。

Try these line..试试这些线..

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

Because when the page gets hoisted, your code gets executed.因为当页面被提升时,你的代码就会被执行。 so they are redirecting here.所以他们重定向到这里。 You need to use preventDefault to stop that.您需要使用 preventDefault 来阻止它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM