Is it possible to change all anchor tags properties on a website at once?

◇◆丶佛笑我妖孽 提交于 2019-12-13 03:38:30

问题


I have recently learned that target="_blank" is vulnerable and we have to use rel="noopener". I am working on a website project where all anchor tags are using the target attribute.

It is possible to change the colors of these anchor texts at once just by using:

a {color: blue;}

in the head of the website.

But If I try to do

a {
rel="noopener"
target ="_blank"
}

The above code does not have any effect. Because rel and target are not covered in CSS.

So how could someone set these attributes for the entire site?

Also, I tried searching on w3schools but they don't have any answer to it in CSS.


回答1:


You're going to need JS.

document.querySelectorAll("a").forEach(a => {
   a.setAttribute("rel", "noopener");
   a.setAttribute("target", "_blank");
});



回答2:


Find elements using Vanilla JS. Loop then change attributes.

document.querySelectorAll('a[target="_blank"]').forEach(function(el){
    el.setAttribute('rel', 'noopener');
});

Then apply CSS

a[target ="_blank"][rel="noopener"] {
    color: blue;
}


来源:https://stackoverflow.com/questions/58670708/is-it-possible-to-change-all-anchor-tags-properties-on-a-website-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!