简体   繁体   English

使用Javascript将“_blank”属性添加到某个div中的所有链接

[英]Using Javascript to add "_blank" attribute to all links in a certain div

I want all links in a certain div (which has a class) to open in a new window.我希望某个 div(有一个类)中的所有链接都在新窗口中打开。

How can this be done using Javascript?如何使用 Javascript 完成此操作?

I'm just learning the basics of Javascript and I came across the following suggestion (from another post on this site), but it does not target all links under the specified class, which is where I'm stuck:我只是在学习 Javascript 的基础知识,我遇到了以下建议(来自本网站上的另一篇文章),但它没有针对指定类下的所有链接,这就是我卡住的地方:

document.getElementsByClassName('vertical-tabs-active-tab')[0].setAttribute("value", "yolo"); document.getElementsByClassName('vertical-tabs-active-tab')[0].setAttribute("value", "yolo");

Try this for div having class as bold :)试试这个为类为粗体的 div :)

var links = document.querySelectorAll("div.bold a");

links.forEach(link => {
    link.setAttribute('target', '_blank');
})

Can't comment on @UtkarshPramodGupta post.无法评论 @UtkarshPramodGupta 帖子。 It's his proposed solution but you need querySelectorAll instead of querySelector:这是他提出的解决方案,但您需要 querySelectorAll 而不是 querySelector:

var links = document.querySelectorAll("div.bold a");

links.forEach(link => {
    link.setAttribute('target', '_blank');
})

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

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