简体   繁体   English

如何通过在HTML标签上获取属性来更改CSS属性?

[英]How do I change a CSS attribute by getting an attribute on an HTML tag?

I need to write this in Javascript but I'm a noob. 我需要用Javascript编写,但我是菜鸟。 Already looked for help on www.w3schools.com but it seems it will take an era to find out this simple answer. 已经在www.w3schools.com上寻求帮助,但似乎需要一个时代才能找到这个简单的答案。

if (some 'a' tag has this href attribute 'href="http://www.mysite.com.br"') {
    style="display:none;"
}

Thank you. 谢谢。

CSS solution (applies by default to all matching elements) CSS解决方案(默认情况下适用于所有匹配元素)

a[href="http://www.mysite.com.br"] { 
  display: none;
}

Javascript solution (can be triggered on events) Javascript解决方案(可以在事件上触发)

var links = document.querySelectorAll('a[href="http://www.mysite.com.br"]')
links.forEach(function (element) {
  element.style.display = 'none'
})

You can simply loop through all a tags and hide the one with the href you want. 您可以简单地遍历所有标签,并用所需的href隐藏该标签。

 $('a').each(function(){ if($(this).attr('href') == "http://www.mysite.com.br") { $(this).css('display',"none"); } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="http://example.com">Example</a> <a href="http://www.mysite.com.br">this should be hidden</a> <a href="http://example2.com">Example 2</a> <a href="http://example3.com">Example 3</a> 

UPDATE 更新

If you do not use jQuery then use the core JS approach: 如果您不使用jQuery,请使用核心JS方法:

 var elements = document.querySelectorAll('a[href="http://www.mysite.com.br"]'); for (var i = 0; i < elements.length; ++i) { elements[i].style.display = "none"; } 
 <a href="http://example.com">Example</a> <a href="http://www.mysite.com.br">this should be hidden</a> <a href="http://example2.com">Example 2</a> <a href="http://example3.com">Example 3</a> 

You could use the CSS [attribute=value] Selector 您可以使用CSS [attribute = value]选择器

 a[href="http://www.google.de/"] { color: red; } 
 <p> Hello </p> <a href="http://www.google.de/">Hello</a> <span>Hello</span> 

You should select the result using a query selector. 您应该使用查询选择器选择结果。 Assuming you want to use vanilla js and not jquery it will be something like: 假设您要使用普通js而不是jquery,它将类似于:

var elements = document.querySelectorAll('a[href="yoursite"]');

and then loop over the results: 然后遍历结果:

for (var i = 0; i < elements.length; ++i) {
  elements[i].style.display = "none";
}

Hope this helps. 希望这可以帮助。

First select your a tag using document.querySelector then using getAttribute() check whether it consist of any url or not, if true then hide a tag , as below, 首先使用document.querySelector选择a tag然后使用getAttribute()检查它是否包含任何url ,如果为true,则hide a tag ,如下所示,

 var a = document.querySelector("a"); var b = a.getAttribute("href"); console.log(b); if(b == "http://www.mysite.com.br"){ a.style.display = "none"; } 
 <a href="http://www.mysite.com.br">Link</a> 

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

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